This is a TL;DR of the standard and semistandard JavaScript rules. For more detailed explanations, see standard's rules documentation.
-
Use 2 spaces 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 after function names.
function name (arg) { ... } // ✓ ok function name(arg) { ... } // ✗ avoid run(function () { ... }) // ✓ ok run(function() { ... }) // ✗ avoid
-
Always use
===instead of==.
Exception:obj == nullis allowed to check fornull || undefined.if (name === 'John') // ✓ ok if (name == 'John') // ✗ avoid if (name !== 'John') // ✓ ok if (name != 'John') // ✗ avoid
-
Always handle the
errfunction 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,consoleandnavigator.window.alert('hi') // ✓ ok
These rules are enforced for standard, but are not imposed in semistandard.