JavaScript Coding style
Coding style
prettier is the tool used to reformat the JavaScript code.
Methods and functions
In JavaScript, functions should use camelCase, but should not capitalizethe first letter. Methods should not use the named function expressionsyntax, because our tools understand method names:
doSomething:function(aFoo,aBar){...}
In-line functions should have spaces around braces, except before commasor semicolons:
functionvalueObject(aValue){return{value:aValue};}
JavaScript objects
varfoo={prop1:"value1"};varbar={prop1:"value1",prop2:"value2"};
Constructors for objects should be capitalized and use Pascal Case:
functionObjectConstructor(){this.foo="bar";}
Operators
In JavaScript, overlong expressions not joined by&&
and||
should break so the operator starts on the second line andstarting in the same column as the beginning of the expression in thefirst line. This applies to?:
, binary arithmetic operatorsincluding+
, and member-of operators. Rationale: an operator at thefront of the continuation line makes for faster visual scanning, asthere is no need to read to the end of line. Also there exists acontext-sensitive keyword hazard in JavaScript; see {{bug(442099, “bug”,19)}}, which can be avoided by putting . at the start of a continuationline, in long member expression.
In JavaScript,==
is preferred to===
.
Unary keyword operators, such astypeof
, should have their operandparenthesized; e.g.typeof("foo")=="string"
.
Literals
Double-quoted strings (e.g."foo"
) are preferred to single-quotedstrings (e.g.'foo'
), in JavaScript, except to avoid escapingembedded double quotes, or when assigning inline event handlers.
Prefixes
k=constant (e.g.
kNC_child
). Not all code uses this style; someusesALL_CAPS
for constants.g=global (e.g.
gPrefService
)a=argument (e.g.
aCount
)JavaScript Specific Prefixes
_=member (variable or function) (e.g.
_length
or_setType(aType)
)k=enumeration value (e.g.
constkDisplayModeNormal=0
)on=event handler (e.g.
functiononLoad()
)Convenience constants for interface names should be prefixed with
nsI
:constnsISupports=Components.interfaces.nsISupports;constnsIWBN=Components.interfaces.nsIWebBrowserNavigation;
Other advice
Do not compare
x==true
orx==false
. Use(x)
or(!x)
instead.x==true
, is certainly different from if(x)
! Compare objects tonull
, numbers to0
or strings to""
, if there is chance for confusion.Make sure that your code doesn’t generate any strict JavaScriptwarnings, such as:
Duplicate variable declaration.
Mixing
return;
withreturnvalue;
Undeclared variables or members. If you are unsure if an arrayvalue exists, compare the index to the array’s length. If you areunsure if an object member exists, use
"name"
inaObject
,or if you are expecting a particular type you may usetypeof(aObject.name)=="function"
(or whichever type you areexpecting).
Use
['value1,value2']
to create a JavaScript array in preferenceto usingnew{{JSxRef("Array","Array","Syntax",1)}}(value1,value2)
which can be confusing, asnewArray(length)
will actually createa physically empty array with the given logical length, while[value]
will always create a 1-element array. You cannot actuallyguarantee to be able to preallocate memory for an array.Use
{member:value,...}
to create a JavaScript object; auseful advantage overnew{{JSxRef("Object","Object","",1)}}()
is the ability to create initial properties and use extendedJavaScript syntax, to define getters and setters.If having defined a constructor you need to assign defaultproperties, it is preferred to assign an object literal to theprototype property.
Use regular expressions, but use wisely. For instance, to check that
aString
is not completely whitespace use/\S/.{{JSxRef("RegExp.test","test(aString)","",1)}}
. Only use{{JSxRef(“String.search”, “aString.search()”)}} if you need to knowthe position of the result, or {{JSxRef(“String.match”,“aString.match()”)}} if you need to collect matching substrings(delimited by parentheses in the regular expression). Regularexpressions are less useful if the match is unknown in advance, or toextract substrings in known positions in the string. For instance,{{JSxRef(“String.slice”, “aString.slice(-1)”)}} returns the lastletter inaString
, or the empty string ifaString
is empty.