Published: 2014-09-21
Updated: 2015-05-17
Target of these practices is to minimize the risk of using the JavaScript programming language, and to reach a maximum of readability.
Write "use strict";
on top of any module.
Always use var
when defining variables.
This is required in strict mode.
Terminate every statement by a ;
(semicolon).
Use ===
and !==
instead of ==
and !=
And thus prove that none of your variables changed its type on the fly.
Don't use null
, use undefined
instead.
One of them is dispensable, and undefined
is inevitable.
Avoid new
and this
. Avoid instanceof
.
They can lead to very hard to find bugs. Code that speculates with "classes" is error-prone.
Test for undefined
using a simple if ( ! x ) ...;
Avoid (typeof x === "undefined")
expressions. Free undefined variables will be detected by strict mode. Use typeof
only to test the existence of external JS library objects.
Use functional inheritance.
All other inheritance variants are error-prone expert tasks.
Put any non-function code into a self-executing function.
Never use the global scope for variables and private functions.
For better readability, do not use $
or _
in identifiers.
Leave these characters to shared libraries like jQuery or underscore.
Pass dependencies as function parameters.
Try to not use global objects and functions, pass any dependency as parameter.
Don't use navigator
to identify browser vendors, better test for browser features.
For example if (window.stop) window.stop();
- but don't use document.all
to identify IE !
Don't use arrays as maps, their length
would be zero then.
When using a for-in loop, wrap the loop body into a hasOwnProperty()
condition.
Or use JQuery.each()
.
Don't use eval()
.
Document every function, its parameters, its return.
In an untyped language like JS this is the quickest way to express how to use code.
And, if you are not sure about whether readability and documentation (comments) are important: imagine coming back after three years and having to fix and extend your code :-)
If the intent of your code is clear, it can always be fixed to do what was intended.
If the intent is not clear, your code could be misinterpreted and the author might "lose face".
Finding out what some code was expected to do at the time of its writing is harder than expected. Write a comment about why you are doing something, not about what you are doing!