block by roachhd 216780576741398678a2

JavaScript Code Style, Mr Doob style 😎

JavaScript CodeStyle

General Provisions

Naming

Naming should be as descriptive as possible. The only exception is the indexing variable in an loop. That can be shortened to a single letter starting from i.

Private properties and methods of objects begin with an underscore _.

Literals

Objects

good:

var obj = { A: 1, b: 2, C: 3 };

var obj = {
    A: 1, 
    b: 2, 
    C: 3 
};

poor:

var obj = {A:1,b:2,C:3};

var obj = {A:1, b:2, C:3};

var obj = {A : 1, b : 2, C : 3};

var obj = { "A" : 1, "b" : 2, "C" : 3 };

var obj = { A : 1, b : 2, C : 3 };

var obj = { A :1, b :2, C :3 };

var obj = { A : 1 , b : 2 , C : 3 };

var obj = {
    A : 1, 
    b : 2, 
    C : 3, 
};


var obj = {
    A : 1 
  , b : 2
  , C : 3 
};

Arrays

good:

var arr = [ 1, 2, 3 ];

var arr = [
    1, 
    2, 
    3 
];

poor:

var arr = [1,2,3];

var arr = [1, 2, 3];

var arr = [ 1 , 2 , 3 ];

var arr = [
    1, 
    2, 
    3,
];

var arr = [
    1
  , 2
  , 3 
];

Strings

Strings are written using single quotes or double quotes:

good:

var  lyrics  =  'Never gonna Give you up, Never gonna Let you down' ;
var  lyrics  =  "Never gonna Give you up, Never gonna Let you down" ;

Semicolon

Semicolon are always placed.

Blocks

good:

if ( a === 0 ) {

   // this is good
   return true;

}

poor:

if ( a === 0 ) {
    // this is good
    return true;

}

if ( a === 0 ) {

    // this is good
    return true;
}

if ( a === 0 ) { // this is good

    return true;

}

if ( a === 0 ){

   // this is good
   return true;

}

Conditional instructions

if statement

good:

if ( test ) { 

    // ... 

} else { 

    // ... 

}

poor:

if (test) { 

    // ... 

}

if( test ) { 

    // ... 

}

if (test ) { 

    // ... 

}

if ( test) { 

    // ... 

}

if ( test ){ 

    // ... 

}

if ( test ) { 

    // ... 

}else { 

    // ... 

}

if ( test ) { 

    // ... 

} else{ 

    // ... 

}

switch

good:

switch ( value ) { 

    case 1 : 

        // ... 
        break ;

    case 2 : 

        // ... 
        break ;

    default : 

        // ... 
        // no break keyword on the last case 

}

Cycles

for

Operators

with

Operator with not used.

The equality operator

Always use strict equality === (inequality !== ).

Ternary operator

Always use spaces around the colon and question mark.

Unary

All unary operators are written together with the following operands:

var foo = ! bar;

eval

Avoid using eval. To parse json using JSON.parse.

undefined

Check the value through a strict comparison.

Good:

x === undefined;

Poor:

/ / In modern browsers already defined immutable undefined. 
var undefined; 
x === undefined;

typeof x === 'undefined'

x === void 0