The Bad Parts
Avoid these altogether
==
and!=
: Don't function properly when result is false, use===
or!==
insteadwith
statement: Intended to provide a shortcut to properties of an object but results vary every time it is runeval
: Adds unnecessary complication and compromises the security of the application- Giving string arguments to
setTimeout
andsetInterval
should also be avoided as this makes them act likeeval
- Giving string arguments to
continue
statement: Forces a loop into its next iteration but the code is usually much improved when re-written withoutcontinue
switch
fall through: In aswitch
statement, eachcase
falls through to the nextcase
unless you explicityly disrup the flow, but using these intentional fall throughs makes the unintentional ones that are causing errors basically impossible to find- This is one of those parts of JavaScript that appears useful but you're better off avoiding because it's occasionally very dangerous
- Block-less statements: Always use curly braces
{}
to block in statements so as to avoid misinterpretation and aid error finding - Bitwise operators: Shouldn't really be doing this kind of manipulations because they are quite slow in JavaScript, therefore there shouldn't be a need to use
&
,|
,ˆ
,˜
,>>
,>>>
or<<
- This doesn't mean you can't use
&&
for example
- This doesn't mean you can't use
++
and--
: This one seems debatable to me; Douglas Crockford finds it makes his coding style much more cryptic and difficult to read (the book uses+=1
and-=1
instead)
The function statement vs the function expression: To use JavaScript well, important to understand that functions are values.
- A function statement is shorthand for a var statement with a function value, so
function foo() {}
(a function statement) means pretty much the same asvar foo = function foo(){};
(a function expression) - Logically, to write the language well you should define a function before using it, but in JavaScript, function statements (using just
function foo(){}
) are hoisted to the top of the scope in which they are defined - this encourages sloppy programming and should be avoided - function statements also don't function consistently in
if
statements - if you need to start a function expression with the word function, wrap it in parentheses (), or JavaScript assumes it's a function statement
Typed wrappers:
Don't use new Boolean
or new String
or new Number
, it's completely unnecessary. Also avoid new Object
and new Array
and use {}
and []
instead.
new
operator:
Functions that are intended to be used with new
(conventionally starting with a capital letter) should be avoided (don't define them) as they can cause all kinds of issues and complex bugs which are difficult to catch.
void:
In JavaScript, this actually takes a value and returns undefined
, which is hugely confusing and not helpful. Don't use it.