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
iforwhilestatements. -
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 utilizesevalcan be challenging. -
Do not use
withstatements, as they modify the scope chain and can cause confusion. -
When using
setTimeoutandsetInterval, make sure to always pass functions as arguments. -
Avoid using
Arrayas associative arrays. Instead, useObject. The functionality provided byArrayfor associative arrays is actually provided by theObjectprototype. Thus, you can achieve the same result using aDateobject. -
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
ObjectandArray. 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