Primitives: When you access a primitive type you work directly on its value.
stringnumberbooleannullundefinedvar foo = 1;var bar = foo;bar = 9;consolelogfoo bar; // => 1, 9
Complex: When you access a complex type you work on a reference to its value.
objectarrayfunctionvar foo = 1 2;var bar = foo;bar0 = 9;consolelogfoo0 bar0; // => 9, 9
Use the literal syntax for object creation.
// badvar item = ;// goodvar item = {};
Don't use reserved words as keys. It won't work in IE8. More info.
// badvar superman =default: clark: 'kent'private: true;// goodvar superman =defaults: clark: 'kent'hidden: true;
Use readable synonyms in place of reserved words.
// badvar superman =class: 'alien';// badvar superman =klass: 'alien';// goodvar superman =type: 'alien';
Use the literal syntax for array creation.
// badvar items = ;// goodvar items = ;
Use Array#push instead of direct assignment to add items to an array.
var someStack = ;// badsomeStacksomeStacklength = 'abracadabra';// only to be used when performance is the main goal, as it's faster that push() method.(for example, populating an array with 1000 elements)// goodsomeStackpush'abracadabra';
When you need to copy an array use Array#slice. jsPerf
var len = itemslength;var itemsCopy = ;var i;// badfor i = 0; i < len; i++itemsCopyi = itemsi;// gooditemsCopy = itemsslice;
To convert an array-like object to an array, use Array#slice.
var args = Arrayprototypeslicecallarguments;
Use single quotes '' for strings.
// badvar name = "Bob Parr";// goodvar name = 'Bob Parr';// badvar fullName = "Bob " + thislastName;// goodvar fullName = 'Bob ' + thislastName;
Strings longer than 100 characters should be written across multiple lines using string concatenation.
Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion.
// badvar errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';// badvar errorMessage = 'This is a super long error that was thrown because \of Batman. When you stop to think about how Batman had anything to do \with this, you would get nowhere \fast.';// goodvar errorMessage = 'This is a super long error that was thrown because ' +'of Batman. When you stop to think about how Batman had anything to do ' +'with this, you would get nowhere fast.';
When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE: jsPerf.
var items;var messages;var length;var i;messages =state: 'success'message: 'This one worked.'state: 'success'message: 'This one worked as well.'state: 'error'message: 'This one did not work.';length = messageslength;// baditems = '<ul>';for i = 0; i < length; i++items += '<li>' + messagesimessage + '</li>';return items + '</ul>';// gooditems = ;for i = 0; i < length; i++// use direct assignment in this case because we're micro-optimizing.itemsi = '<li>' + messagesimessage + '</li>';return '<ul>' + itemsjoin'' + '</ul>';
Function expressions:
// anonymous function expressionvarreturn true;;// named function expressionvarreturn true;;// immediately-invoked function expression (IIFE)consolelog'Welcome to the Internet. Please follow me.';;
Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news.
Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.
// badif currentUserconsolelog'Nope.';// goodvar test;if currentUserconsolelog'Yup.';;
Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.
// bad// ...stuff...// good// ...stuff...
Use dot notation when accessing properties.
var luke =jedi: trueage: 28;// badvar isJedi = luke'jedi';// goodvar isJedi = lukejedi;
Use subscript notation [] when accessing properties with a variable.
var luke =jedi: trueage: 28;return lukeprop;var isJedi = ;
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.
// badsuperPower = ;// goodvar 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.
// badvar i len dragonballitems =goSportsTeam = true;// badvar i;var items = ;var dragonball;var goSportsTeam = true;var len;// goodvar items = ;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.
// badtest;consolelog'doing stuff..';//..other stuff..var name = ;if name === 'test'return false;return name;// goodvar name = ;test;consolelog'doing stuff..';//..other stuff..if name === 'test'return false;return name;// bad - unnecessary function callvar name = ;if !argumentslengthreturn false;this;return true;// goodvar name;if !argumentslengthreturn false;name = ;this;return true;
You should always use try…catch statements in your code. It will prevent that the whole website stops working because os an error in one part of the logic. The show must go on, don't let an error to ruin the UX.
// badvar user = ;var userData;// If the data comes not well formed, so the WHOLE app will stop runninguserData = JSONparsedata;usersetData = userData;// goodvar user = ;var output = false;var userData;tryuserData = JSONparsedata;usersetData = userData;output = true;catch err// Now the app continues working and we can let the user know that there was an error and the cause.UI;finallyreturn output;
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.
// badvar i len dragonballitems =goSportsTeam = true;// badvar i;var items = ;var dragonball;var goSportsTeam = true;var len;// goodvar items = ;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.
// badtest;consolelog'doing stuff..';//..other stuff..var name = ;if name === 'test'return false;return name;// goodvar name = ;test;consolelog'doing stuff..';//..other stuff..if name === 'test'return false;return name;// bad - unnecessary function callvar name = ;if !argumentslengthreturn false;this;return true;// goodvar name;if !argumentslengthreturn false;name = ;this;return true;
Variable declarations get hoisted to the top of their scope, but their assignment does not.
// we know this wouldn't work (assuming there// is no notDefined global variable)consolelognotDefined; // => throws a ReferenceError// creating a variable declaration after you// reference the variable will work due to// variable hoisting. Note: the assignment// value of `true` is not hoisted.consolelogdeclaredButNotAssigned; // => undefinedvar declaredButNotAssigned = true;// The interpreter is hoisting the variable// declaration to the top of the scope,// which means our example could be rewritten as:var declaredButNotAssigned;consolelogdeclaredButNotAssigned; // => undefineddeclaredButNotAssigned = true;
Anonymous function expressions hoist their variable name, but not the function assignment.
consoleloganonymous; // => undefined; // => TypeError anonymous is not a functionvarconsolelog'anonymous function expression';;
Named function expressions hoist the variable name, not the function name or the function body.
consolelognamed; // => undefined; // => TypeError named is not a function; // => ReferenceError superPower is not definedvarconsolelog'Flying';;// the same is true when the function name// is the same as the variable name.consolelognamed; // => undefined; // => TypeError named is not a functionvarconsolelog'named';
Function declarations hoist their name and the function body.
; // => Flyingconsolelog'Flying';
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.
=== and !== over == and !=.Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules:
'', otherwise trueif 0// true// An array is an object, objects evaluate to true
Use shortcuts.
// badif name !== ''// ...stuff...// goodif name// ...stuff...// badif collectionlength > 0// ...stuff...// goodif collectionlength// ...stuff...
For more information see Truth Equality and JavaScript by Angus Croll.
Use braces with all multi-line blocks.
// badif testreturn false;// goodif testreturn false;// badreturn false;// goodreturn false;
If you're using multi-line blocks with if and else, put else on the same line as your
if block's closing brace.
// badif test;;else;// goodif test;;else;
Use /** ... */ for multi-line comments. Include a description, specify types and values for all parameters and return values.
// bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} element// ...stuff...return element;// good/*** make() returns a new element* based on the passed in tag name** @param {String} tag* @return {Element} element*/// ...stuff...return element;
Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.
// badvar active = true; // is current tab// good// is current tabvar active = true;// badconsolelog'fetching type...';// set the default type to 'no type'var type = this_type || 'no type';return type;// goodconsolelog'fetching type...';// set the default type to 'no type'var type = this_type || 'no type';return type;
Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME -- need to figure this out or TODO -- need to implement.
Use // FIXME: to annotate problems.
// FIXME: shouldn't use a global heretotal = 0;return this;
Use // TODO: to annotate solutions to problems.
// TODO: total should be configurable by an options paramthistotal = 0;return this;
Use soft tabs set to 4 spaces.
// badvar name;// bad∙var name;// good∙∙∙∙var name;
Place 1 space before the leading brace.
// badconsolelog'test';// goodconsolelog'test';// baddog;// gooddog;
Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space before the argument list in function calls and declarations.
// badifisJedi;// goodif isJedi;// badconsole;// goodconsolelog'Swooosh!';
Set off operators with spaces.
// badvar x=y+5;// goodvar x = y + 5;
End files with a single newline character.
// bad// ...stuff...this;
// bad// ...stuff...this;↵↵
// good// ...stuff...this;↵
Use indentation when making long method chains. Use a leading dot, which emphasizes that the line is a method call, not a new statement.
// badfind'.selected'find'.open';// badfind'.selected'find'.open';// goodfind'.selected'find'.open';// badvar leds = stagedatadata* 2+ ',' + radius + margin + ')'calltronled;// goodvar leds = stagedatadata* 2+ ',' + radius + margin + ')'calltronled;
Leave a blank line after blocks and before the next statement
// badif fooreturn bar;return baz;// goodif fooreturn bar;return baz;// badvar obj =;return obj;// goodvar obj =;return obj;
Leading commas: Nope.
// badvar story =onceuponaTime;// goodvar story =onceuponaTime;// badvar hero =firstName: 'Bob'lastName: 'Parr'heroName: 'Mr. Incredible'superPower: 'strength';// goodvar 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.
// badvar hero =firstName: 'Kevin'lastName: 'Flynn';var heroes ='Batman''Superman';// goodvar hero =firstName: 'Kevin'lastName: 'Flynn';var heroes ='Batman''Superman';
Yup.
// badvar name = 'Skywalker'return name// goodvar name = 'Skywalker';return name;;// good (guards against the function becoming an argument when two files with IIFEs are concatenated);var name = 'Skywalker';return name;;
Strings:
// => this.reviewScore = 9;// badvar totalScore = thisreviewScore + '';// goodvar totalScore = '' + thisreviewScore;// badvar totalScore = '' + thisreviewScore + ' total score';// goodvar totalScore = thisreviewScore + ' total score';
Use parseInt for Numbers and always with a radix for type casting.
var inputValue = '4';// badvar val = inputValue;// badvar val = +inputValue;// badvar val = inputValue >> 0;// badvar val = parseIntinputValue;// goodvar val = NumberinputValue;// goodvar val = parseIntinputValue 10;
If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.
// good/*** parseInt was the reason my code was slow.* Bitshifting the String to coerce it to a* Number made it a lot faster.*/var val = inputValue >> 0;
Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but Bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
2147483647 >> 0 //=> 21474836472147483648 >> 0 //=> -21474836482147483649 >> 0 //=> -2147483647
Booleans:
var age = 0;// badvar hasAge = age;// goodvar hasAge = Booleanage;// goodvar hasAge = !!age;
Avoid single letter names. Be descriptive with your naming.
// bad// ...stuff...// good// ..stuff..
Use camelCase when naming objects, functions, and instances.
// badvar OBJEcttsssss = {};var this_is_my_object = {};var o = {};{}// goodvar thisIsMyObject = {};{}
Use PascalCase when naming constructors or classes.
// badthisname = optionsname;var bad =name: 'nope';// goodthisname = optionsname;var good =name: 'yup';
Use a leading underscore _ when naming private properties.
// badthis__firstName__ = 'Panda';thisfirstName_ = 'Panda';// goodthis_firstName = 'Panda';
When saving a reference to this use _this.
// badvar self = this;returnconsolelogself;;// badvar that = this;returnconsolelogthat;;// goodvar _this = this;returnconsolelog_this;;
Name your functions. This is helpful for stack traces.
// badvarconsolelogmsg;;// goodvarconsolelogmsg;;
Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.
If your file exports a single class, your filename should be exactly the name of the class.
// file contents// ...moduleexports = CheckBox;// in some other file// badvar CheckBox = require'./checkBox';// badvar CheckBox = require'./check_box';// goodvar CheckBox = require'./CheckBox';
If you do make accessor functions use getVal() and setVal('hello').
// baddragon;// gooddragon;// baddragon;// gooddragon;
If the property is a boolean, use isVal() or hasVal().
// badif !dragonreturn false;// goodif !dragonreturn false;
It's okay to create get() and set() functions, but be consistent.
options || options = {};var lightsaber = optionslightsaber || 'blue';this;thiskey = val;;return thiskey;;
Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!
consolelog'new jedi';// badconsolelog'fighting';consolelog'blocking';;// goodconsolelog'fighting';;consolelog'blocking';;
Methods can return this to help with method chaining.
// badthisjumping = true;return true;;thisheight = height;;var luke = ;luke; // => trueluke; // => undefined// goodthisjumping = true;return this;;thisheight = height;return this;;var luke = ;luke;
It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
options || options = {};thisname = optionsname || 'no name';return thisname;;return 'Jedi - ' + this;;
When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
// bad;;
prefer:
// good;;
Use event delegation ALWAYS. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. Understanding how events propagate is an important factor in being able to leverage Event Delegation. Any time one of our anchor tags is clicked, a click event is fired for that anchor, and then bubbles up the DOM tree, triggering each of its parent click event handlers. This means that anytime you click one of our bound anchor tags, you are effectively clicking the entire document body! This is called event bubbling or event propagation.
// bad;// This affects the performance as it's listening for the all the events in all the DOM. Performance matters.;
prefer:
// good;
Prefix jQuery object variables with a $.
// badvar sidebar = ;// goodvar $sidebar = ;
Cache jQuery lookups.
// bad;// ...stuff...;// goodvar $sidebar = ;$sidebar;// ...stuff...$sidebar;
For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf
Use find with scoped jQuery object queries.
// bad;// badfind'ul';// good;// good;// good$sidebarfind'ul';
Read This
Tools
Other Style Guides
Other Styles
Further Reading
Books
Blogs