- RULE: Identifiers bound to constructors must start with a capital.
// GOODvarUser=function(name,age){this.name=name;this.age=age;};varuser=newUser('bob',32);// BADvaruser=function(name,age){this.name=name;this.age=age;};varu=newuser('bob',32);- RULE: Identifiers bound to a variable or function must start with a minuscule.
- RULE: Identifiers bound to a variable or function must be CamelCased or lowercase, depending on their length.
// GOODvarsomeKindOfProcess=function(){};vartmpvar=42;// BADvarsome_kind_of_process=function(){};varsomekindofprocess=function(){};- RULE: Variables must always be declared, prior to use.
- RULE: Variable declarations should appear at the top of functions, and not inside other blocks. The exception is for loops.
Variable declarations are moved up to the top of the function scope anyway, so that's where they belong.
// GOODfunction(a,b){vark;if(a==b){k=true;}
...
}for(vari=0;i<l;i++){ ... }// BADfunction(a,b){if(a==b){vark=true;}
...
}- RULE: Control-flow statements, such as
if,whileandformust have a space between the keyword and the left parenthesis.
They aren't functions, and thus better distinguished like this.
// GOODif(a){returntrue;}// BADif(a){returntrue;}- RULE: Anonymous functions must have a space between the
functionkeyword and the left parenthesis.
To emphasise the lack of identifier and differentiate them with named functions.
// GOODfunction(a,b){}// BADfunction(a,b){}- RULE: Named functions must not have a space between the function name and the left parenthesis.
- RULE: Function calls should not have a space between the function name and the left parenthesis.
// GOODfunctionadd(a,b){}// BADfunctionadd(a,b){}- RULE: Semicolons
;must be added at the end of every statement, except when the next character is a closing bracket}. In that case, they may be omitted.
// GOODvarf=functionadd(a,b){if(a==b){returna*2}// No `;` here.returna+b;};// BADvarf=functionadd(a,b){returna+b}- RULE: Braces should be used in all circumstances. They may be omitted around simple statements.
// GOODif(x){returntrue}// BADif(x)while(1)i++;else
...// OKif(x)returntrue;// OKif(x)returntrue;- RULE: Opening Braces must never be on a line of their own.
Vertical screen space is precious.
// GOODif(x){returntrue;}// BADif(x){returntrue;}// BADif(x){returntrue;}