Things to avoid in JavaScript (the bad parts)
By Flavio Copes
A list of things to avoid when writing JavaScript, like using new Object() over literals, == instead of ===, eval, with, and editing built-in prototypes.
JavaScript lets you do a few things it probably shouldn’t. Here’s my list of the parts of the language to avoid, what to use instead, and why.
-
Avoid creating a new object by using
new Object(). Use the object literal syntax{}instead. It’s shorter, it reads better, and it does the same thing. -
Same thing for arrays, favor
[]overnew Array(). Also,new Array(3)does not create an array containing the number 3, but an empty array with alengthof 3. -
Avoid blocks except where statements require them (
if,switch, loops,try). A standalone block looks like it creates a new scope, but it doesn’t: only functions create scope, so the block just misleads whoever reads the code. -
Never assign inside an
iforwhilestatement condition part.if (x = 5)assigns 5 toxand then evaluates it as truthy, so the branch always runs. Almost always it’s a mistyped==, and it’s very hard to spot. -
Never use
==and!=. Use===and!==instead. The double equals coerces types before comparing, following rules nobody remembers.0 == ''istrue,0 == '0'istrue, but'' == '0'isfalse. With===different types are never equal, no surprises. -
Never use
eval. Why? It has performance issues (it runs the interpreter/compiler), it has security issues (code injection if used with user input), difficulties in debugging. To access a property from a dynamic name, bracket notation does the same job safely. -
Never use
with, as it modifies the scope chain and can be a source of confusion. Inside awithblock you can’t tell if a variable refers to a property of the object or to something in an outer scope, and neither can the JavaScript engine, which makes it slow too. -
Always pass functions to
setTimeoutandsetInterval. If you pass a string instead, the browser evaluates it likeevaldoes, with the same problems. -
Never use
Arrayas an associative arrays, useObjectinstead. The part of theArrayobject that provides that functionality is in fact provided by theObjectprototype, so you could really have used aDateobject for that same thing. String keys on an array are just regular object properties: they don’t count inlengthand array methods ignore them. -
Don’t use
\at the end of a string to create a multiline string. It’s fragile: a single invisible space after the backslash turns it into a syntax error. Use string concatenation' string1 ' + ' string2 'instead. -
Never modify the prototypes of the built-in objects
ObjectandArray. Your added method shows up in every object in the program, and it can collide with libraries or with methods added to the language later. Modify other prototypes of other objects such asFunctionwith caution as it could lead to bugs hard to debug.
Related posts about js: