Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing JavaScript code.
Avoid Using for-in Loop for Arrays
We should avoid using for-in loop for arrays.
For instance, instead of writing:
let sum = 0;
for (let i in arrayNumbers) {
sum += arrayNumbers[i];
}
We can use a for loop or a for-of loop:
let sum = 0;
for (let a of arrayNumbers) {
sum += a;
}
or:
let sum = 0;
for (let i = 0, len = arrayNumbers.length; i < len; i++) {
sum += arrayNumbers[i];
}
A for-in loop is used for iterating through regular objects rather than arrays.
Pass Functions, not Strings, to setTimeout() and setInterval()
We should always pass functions to setTimeout
and setInterval
.
For example, instead of writing:
setInterval('doSomething()', 1000);
setTimeout('doSomething()', 5000);
We write:
setInterval(doSomething, 1000);
setTimeout(doSomething, 5000);
Use a switch/case Statement Instead of a Series of if/else
switch
and case
are shorter than a series of if
and else
.
For example, we can write;
switch (val) {
case 1:
//...
break;
case 2:
//...
break;
case 3:
//...
break;
case 4:
//...
break;
default:
//...
}
This is better organized than:
if (val === 1) {
//...
}
else if (val === 2) {
//...
}
else if (val === 3) {
//...
}
else if (val === 4) {
//...
}
else {
//...
}
If we have more than 10 cases, we should avoid a series of if
and else
s.
Use switch/case Statement with Numeric Ranges
We can use switch
and case
with numeric ranges.
To do that, we can write:
switch (true) {
case isNaN(age):
category = "not an age";
break;
case (age >= 50):
category = "old";
break;
case (age <= 20):
category = "kid";
break;
default:
category = "young";
break;
};
Instead of passing a variable switch
, we pass in true
.
Also, the case
has expressions instead of a value.
Create an Object Whose Prototype is a Given Object
We can create an object whose prototype is the gin object with he Object.create
method.
For example, we can write:
const obj = Object.create(proto);
where proto
is the prototype object for obj
.
An HTML Escaper Function
We can escape HTML with some regex.
For example, we can write:
function escapeHTML(text) {
const replacements = {
"<": "<",
">": ">",
"&": "&",
""": """
};
return text.replace(/[<>&"]/g, (character) => {
return replacements[character];
});
}
We search for the brackets, ampersands, and quotes with the regex and then we get the replacement character from the replacements
object.
Avoid Using try-catch-finally Inside a Loop
try-catch-finally creates a new variable in the current scope at runtime each time the catch
clause is run.
So instead of writing:
let arr = ['foo', 'bar'], i;
for (i = 0, len = arr.length; i < len; i++) {
try {
// ...
} catch (e) {
// ...
}
}
We write:
let arr = ['foo', 'bar'], i;
try {
for (i = 0, len = arr.length; i < len; i++) {
// ...
}
} catch (e) {
// ...
}
Now the catch
clause can only be run once with the 2nd example.
So variables in there can only be created once.
Conclusion
We shouldn’t use for-in loops with arrays.
Also, we can create objects with a prototype with Object.create
.
There’re also many things to watch out for with arrays.