Here is a quick list of things to avoid when writing JavaScript code:
-
Avoid creating a new object by using
new Object()
. Instead, use the object literal syntax{}
. -
Similarly, when creating arrays, favor
[]
overnew Array()
. -
Avoid unnecessary blocks, unless they are required by statements such as
if
,switch
, loops, ortry
. -
Avoid assigning values inside the condition part of
if
orwhile
statements. -
Never use loose equality operators
==
and!=
. Always use strict equality operators===
and!==
instead. -
Avoid using
eval
. This function has performance issues, as it runs the interpreter/compiler. It also poses security risks, such as code injection when used with user input. Additionally, debugging code that utilizeseval
can be challenging. -
Do not use
with
statements, as they modify the scope chain and can cause confusion. -
When using
setTimeout
andsetInterval
, make sure to always pass functions as arguments. -
Avoid using
Array
as associative arrays. Instead, useObject
. The functionality provided byArray
for associative arrays is actually provided by theObject
prototype. Thus, you can achieve the same result using aDate
object. -
Do not use
\
at the end of a string to create a multiline string, as it is not part of ECMAScript. Instead, use string concatenation'string1 ' + 'string2'
. -
Never modify the prototypes of built-in objects such as
Object
andArray
. If you need to modify other prototypes, such asFunction
, do so with caution, as it can lead to hard-to-debug bugs.
Tags: JavaScript, programming, best practices