DEV Community

Santosh Viswanatham
Santosh Viswanatham

Posted on • Originally published at Medium on

9 tiny tips to make your JavaScript code run faster

Photo by Marc Sendra Martorell on Unsplash

Cleaning up a 5 year old code base introduced me to lot of bad practices which every developer usually does(Including me). Being an extra pair of eyes to look at the code helped me to understand whats happening underneath and How we could improve to make the same functionality/code run faster than before.

Here are few of the Interesting approaches I noticed and ways to write it in a better way to improve the performance of your code.

Use if-else for comparing Boolean, else use switch

Is your code stuck up in an if — else if — else if… hell? Move to switch instead. Use if, only if you have to compare one condition, if-else to compare Boolean. For the rest use switch.

Use indexOf to get the position in an array and includes if you just want to know if it exists

If you would like to know if an element exists in an array of elements then use Array.includes, If you want the exact position of the element, only then use Array.indexOf

Instead of comparing if(names.indexOf(‘javascript’) > -1){} use if(names.includes(‘javascript’)){}

Cloning an Object

Is it a single level object? Use spread operator const copiedObj = {...obj} to copy the object

Is is a multi level nested object? Use JSON methods instead const copiedObj = JSON.parse(JSON.stringify(obj))

Use conditions that return boolean inside conditional statements

If you are using conditional statements like if or else if then use a condition that returns a Boolean instead of using a value that is implicitly type casted to a Boolean.

Use strong type checking

Use strong type checking for every comparison. For example, use typeof undefined === “undefined” instead of undefined == undefined which will also return true for null == undefined. This is more of a good coding practice to avoids surprises later on.

Start using Functional Programming, Write Independent Functions

Without even knowing, I realized that I was using Functional Programming for a long time now. Functional Programming is a programming paradigm where functions are the major building blocks of your code. Putting it in simple words to my understanding, It is more like writing independent functions that take input, processes the input and outputs the processed value. The function is independent of any external or global variable changes. This minimizes scope chain, makes it easy to move a code snippet between components, services without any dependencies.

Minimize scope chains

Lets us consider the below example. Which approach is less expensive? Clearly, the second approach is a better one. Why? The second approach uses local variables to that particular function scope, while the first one access variables from the global window object. Keeping your scope chains to the minimum is faster and less expensive.

// Approach 1 
const number1 = 10, number2 = 15;
function add(): number {
  return number1 + number2; // returns 25
}

add();

// Approach 2
const number1 = 10, number2 = 15;
function add(num1: number, num2: number): number {
  return number1 + number2; // returns 25
}

add(number1, number2);

Keep DOM Interactions to the minimum

Every DOM Interaction will access the global objects(document, window, etc.) which is time-consuming. Keeping them to the minimum would improve the performance of your code. For example, If you would like to perform multiple operations on a DOM element then store it in a variable and access that variable to perform those actions.

// Bad Approach
document.getElementById('username').on('keyup', () => {
  // do something
});
document.getElementById('username').on('keydown', () => {
  // do something
});
document.getElementById('username').on('focus', () => {
  // do something
});

// Good Approach
const usernameInput = document.getElementById('username');

usernameInput.on('keyup', () => {
  // do something
});
usernameInput.on('keydown', () => {
  // do something
});
usernameInput.on('focus', () => {
  // do something
});

Use Typescript

Typescript is a superset of JavaScript which adds additional helpful/useful features to our JavaScript code. One of them is Typings. Static type checking improves your code quality, throws out errors in compile-time rather than runtime. A simple example of the same functional code in both JavaScript and TypeScript is given below.

// sample.js
function add(number1, number2) {
  return number1 + number2;
}
add(4, 5); // 9
add(‘’, 4); // “4”

// sample.ts
function add(number1: number, number2: number): number {
  return number1 + number2;
}
add(4, 5); // 9
add(‘’, 4); // Argument of type ‘“”’ is not assignable to parameter of type ‘number’.

In JavaScript, even add(‘’, 4) returns ‘4’ which is not the ideal output we are expecting. But if you define types in typescript like add(number1: number, number2: number) then it throws out a compile error if you use string instead of a number.

If you have any other tips then share it in the comments. Hope this was helpful. :)

Top comments (4)

Collapse
 
pantitima profile image
Pan-Titima

Thank you. All are helpful. Clean code, more readable and good performance ^

Collapse
 
devcer profile image
Santosh Viswanatham

Thank you. Glad this was helpful.

Collapse
 
freakomonk profile image
freakomonk

Isn't JSON.parse(JSON.stringify(obj)) slow ?

Collapse
 
devcer profile image
Santosh Viswanatham

Yes. it is slow If in case of one level. But It is the fastest approach if you have multiple levels of Nested JSON Object.