Simple Performance tips for JS

·

1 min read

REDUCE ACTIVITY IN LOOPS

Each statement in a loop, including the for statement, is executed for each iteration of the loop.

Bad:

for (let i = 0; i < arr.length; i++) {

Better Code:

let l = arr.length;  
for (let i = 0; i < l; i++) {

Reduce DOM size

Avoid Unnecessary Variables

Bad:

let fullName = firstName + " " + lastName;  
document.getElementById("demo").innerHTML = fullName;

Better Code:

document.getElementById("demo").innerHTML = firstName + " " + lastName;

Reduce DOM Access

Accessing the HTML DOM is very slow, compared to other JavaScript statements.

If you expect to access a DOM element several times, access it once, and use it as a local variable:

Example

const obj = document.getElementById("demo");  
obj.innerHTML = "Hello";