A primarily decent approach to JavaScript
- Whitespace
- Types
- Objects
- Arrays
- Strings
- Functions
- Properties
- Variables
- Comparison Operators & Equality
- Blocks
- Commas
- Semicolons
- Naming Conventions
-
Use soft tabs set to 2 spaces.
// bad function() { ∙∙∙∙var name; } // bad function() { ∙var name; } // good function() { ∙∙var name; }
-
Place 1 space before the leading curly brace.
// bad function test(){ console.log('test'); } // good function test() { console.log('test'); }
-
Place 1 space before the opening parenthesis in control statements (
if
,else if
,while
, etc.).// bad if(isJedi) { fight(); } // good if (isJedi) { fight(); }
-
Place no space before the argument list in function calls and declarations.
// bad function fight () { console.log ('Swooosh!'); } // good function fight() { console.log('Swooosh!'); }
-
Set off operators with spaces.
// bad var x=y+5; // good var x = y + 5;
-
Leave a blank line after blocks and before the next statement
// bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad var obj = { foo: function () { }, bar: function () { } }; return obj; // good var obj = { foo: function () { }, bar: function () { } }; return obj;
-
Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
var foo = 1; var bar = foo; bar = 9; console.log(foo, bar); // => 1, 9
-
Complex: When you access a complex type you work on a reference to its value.
object
array
function
var foo = [1, 2]; var bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
-
Use the literal syntax for generic object creation.
// bad var item = new Object(); // good var item = {};
-
Don't use reserved words as keys. It won't work in IE8. More info.
// bad var superman = { default: { clark: 'kent' }, private: true }; // good var superman = { defaults: { clark: 'kent' }, hidden: true };
-
Use readable synonyms in place of reserved words.
// bad var superman = { class: 'alien' }; // bad var superman = { klass: 'alien' }; // good var superman = { type: 'alien' };
-
Use the literal syntax for array creation.
// bad var items = new Array(); // good var items = [];
-
Use Array#push instead of direct assignment to add items to an array.
var someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
-
Use single quotes
''
for strings.// bad var name = "Bob Parr"; // good var name = 'Bob Parr'; // bad var fullName = "Bob " + this.lastName; // good var fullName = 'Bob ' + this.lastName;
-
Function expressions:
// anonymous function expression var anonymous = function() { return true; }; // named function expression var named = function named() { return true; };
-
Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... }
-
Use dot notation when accessing properties.
var luke = { jedi: true, age: 28 }; // bad var isJedi = luke['jedi']; // good var isJedi = luke.jedi;
-
Use bracket notation
[]
when accessing properties with a variable.var luke = { jedi: true, age: 28 }; function getProp(prop) { return luke[prop]; } var isJedi = getProp('jedi');
-
Always use
var
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.// bad superPower = new SuperPower(); // good var superPower = new SuperPower();
-
Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// bad var i; var items = getItems(); var dragonball; var goSportsTeam = true; var len; // good var items = getItems(); var goSportsTeam = true; var dragonball; var length; var i;
-
Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
// bad function () { test(); console.log('doing stuff..'); //..other stuff.. var name = getName(); if (name === 'test') { return false; } return name; } // good function () { var name = getName(); test(); console.log('doing stuff..'); //..other stuff.. if (name === 'test') { return false; } return name; } // bad - unnecessary function call function () { var name = getName(); if (!arguments.length) { return false; } this.setFirstName(name); return true; } // good function () { var name; if (!arguments.length) { return false; } name = getName(); this.setFirstName(name); return true; }
-
Use
===
and!==
over==
and!=
. -
Conditional statements such as the
if
statement evaluate their expression using coercion with theToBoolean
abstract method and always follow these simple rules:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN, otherwise true
- Strings evaluate to false if an empty string
''
, otherwise true
if ([0]) { // true // An array is an object, objects evaluate to true }
-
Use shortcuts.
// bad if (name !== '') { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0) { // ...stuff... } // good if (collection.length) { // ...stuff... }
-
For more information see Truth Equality and JavaScript by Angus Croll.
-
Use braces with all multi-line blocks.
// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad function () { return false; } // good function () { return false; }
-
If you're using multi-line blocks with
if
andelse
, putelse
on the same line as yourif
block's closing brace.// bad if (test) { thing1(); thing2(); } else { thing3(); } // good if (test) { thing1(); thing2(); } else { thing3(); }
-
Leading commas: Nope.
// bad var story = [ once , upon , aTime ]; // good var story = [ once, upon, aTime ]; // bad var hero = { firstName: 'Bob' , lastName: 'Parr' , heroName: 'Mr. Incredible' , superPower: 'strength' }; // good var hero = { firstName: 'Bob', lastName: 'Parr', heroName: 'Mr. Incredible', superPower: 'strength' };
-
Additional trailing comma: Nope. This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 (source):
Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.
```javascript
// bad
var hero = {
firstName: 'Kevin',
lastName: 'Flynn',
};
var heroes = [
'Batman',
'Superman',
];
// good
var hero = {
firstName: 'Kevin',
lastName: 'Flynn'
};
var heroes = [
'Batman',
'Superman'
];
```
-
Yup.
// bad (function () { var name = 'Skywalker' return name })() // good (function () { var name = 'Skywalker'; return name; })(); // good (guards against the function becoming an argument when two files with IIFEs are concatenated) ;(function () { var name = 'Skywalker'; return name; })();
-
Avoid single letter names. Be descriptive with your naming.
// bad function q() { // ...stuff... } // good function query() { // ..stuff.. }
-
Use camelCase when naming objects, functions, and instances.
// bad var OBJEcttsssss = {}; var this_is_my_object = {}; var o = {}; function c() {} // good var thisIsMyObject = {}; function thisIsMyFunction() {}
-
Use PascalCase when naming classes.
// bad class user { constructor(options) { this.name = options.name; } } var bad = new user({ name: 'nope' }); // good class User { constructor(options) { this.name = options.name; } } var good = new User({ name: 'yup' });
-
Name your functions. This is helpful for stack traces.
// bad var log = function (msg) { console.log(msg); }; // good var log = function log(msg) { console.log(msg); };
-
Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.