This is a TL;DR of the happiness JavaScript rules.
The best way to learn about happiness
is to just install it and give it a try on
your code.
-
Use tabs for indentation.
function hello (name) { console.log('hi', name) }
-
Use single quotes for strings except to avoid escaping.
console.log('hello there') $("<div class='box'>")
-
No unused variables.
function myFunction () { var result = something() // ✗ avoid }
-
Add a space after keywords.
if (condition) { ... } // ✓ ok if(condition) { ... } // ✗ avoid
-
Add a space before a function declaration's parentheses.
function name (arg) { ... } // ✓ ok function name(arg) { ... } // ✗ avoid run(function () { ... }) // ✓ ok run(function() { ... }) // ✗ avoid
-
Always use
===
instead of==
.
Exception:obj == null
is allowed to check fornull || undefined
.if (name === 'John') // ✓ ok if (name == 'John') // ✗ avoid
if (name !== 'John') // ✓ ok if (name != 'John') // ✗ avoid
-
Infix operators must be spaced.
// ✓ ok var x = 2 var message = 'hello, ' + name + '!'
// ✗ avoid var x=2 var message = 'hello, '+name+'!'
-
Commas should have a space after them.
// ✓ ok var list = [1, 2, 3, 4] function greet (name, options) { ... }
// ✗ avoid var list = [1,2,3,4] function greet (name,options) { ... }
-
Keep else statements on the same line as their curly braces.
// ✓ ok if (condition) { // ... } else { // ... }
// ✗ avoid if (condition) { // ... } else { // ... }
-
For multi-line if statements, use curly braces.
// ✓ ok if (options.quiet !== true) console.log('done')
// ✓ ok if (options.quiet !== true) { console.log('done') }
// ✗ avoid if (options.quiet !== true) console.log('done')
-
Always handle the
err
function parameter.// ✓ ok run(function (err) { if (err) throw err window.alert('done') })
// ✗ avoid run(function (err) { window.alert('done') })
-
Always prefix browser globals with
window.
.
Exceptions are:document
,console
andnavigator
.window.alert('hi') // ✓ ok
-
Multiple blank lines not allowed.
// ✓ ok var value = 'hello world' console.log(value)
// ✗ avoid var value = 'hello world' console.log(value)
-
For the ternary operator in a multi-line setting, place
?
and:
on their own lines.// ✓ ok var location = env.development ? 'localhost' : 'www.api.com' // ✓ ok var location = env.development ? 'localhost' : 'www.api.com' // ✗ avoid var location = env.development ? 'localhost' : 'www.api.com'
-
For var declarations, write each declaration in its own statement.
// ✓ ok var silent = true var verbose = true // ✗ avoid var silent = true, verbose = true // ✗ avoid var silent = true, verbose = true
-
Wrap conditional assignments with additional parentheses. This makes it clear that the expression is intentionally an assignment (
=
) rather than a typo for equality (===
).// ✓ ok while ((m = text.match(expr))) { // ... } // ✗ avoid while (m = text.match(expr)) { // ... }
-
Always use semicolons.
window.alert('hi'); // ✓ ok window.alert('hi') // ✗ avoid