JavaScript optimization in 2021 πŸš€

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

17 ways to do JavaScript optimization

You might be using JavaScript development for a long time but sometimes you might not be updated with newest beautiful features that it offers which can solve your issues without writing extra codes. These techniques can help you write clean and optimized JavaScript Code. Moreover, these topics can help you to prepare yourself for JavaScript interviews in 2021.

1. If with multiple conditions

We can store multiple values in the array and we can use the array includes method.

//long
if (x === 'hello' || x === 'hola' || x === 'hallo' || x ==='hej') {
    //logic
}
//short
if (['hello', 'hola', 'hallo', 'hej'].includes(x)) {
   //logic
}

2. If true … else Shorthand

This is a greater shortcut for when we have if-else conditions that do not contain bigger logics inside. We can simply use the ternary operators to achieve this shorthand.

// long
let test= boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// short
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
console.log(test);

3. Null, Undefined, Empty Checks

When we do create new variables sometimes we want to check if the variable we are referencing for its value is not null or undefined. JavaScript does have a really good shorthand to achieve these functions.

// Longhand
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}
// Shorthand
let second = first|| '';

4. Null Value checks and Assigning Default Value

let first = null,
let second = first || '';
console.log("null check", test2); // output will be ""

5. Undefined Value checks and Assigning Default Value

let first= undefined,
let second = first || '';
console.log("undefined check", test2); // output will be ""

6.foreach Loop Shorthand

This is a useful short hand for iteration
// Longhand
for (var i = 0; i < testData.length; i++)

// Shorthand
for (let i in testData) or  for (let i of testData)
Array for each variable
function testData(element, index, array) {
  console.log('test[' + index + '] = ' + element);
}

[11, 24, 32].forEach(testData);
// prints: test[0] = 11, test[1] = 24, test[2] = 32

7. Comparison returns

Using the comparison in the return statement will avoid our 5 lines of code and reduced them to 1 line.

// Longhand
let test;
function checkReturn() {
    if (!(test === undefined)) {
        return test;
    } else {
        return callMe('test');
    }
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
    console.log(val);
}
// Shorthand
function checkReturn() {
    return test || callMe('test');
}

8. Short function calling

We can achieve these types of functions using ternary operator.

// Longhand
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}
// Shorthand
(test3 === 1? test1:test2)();

9. Switch shorthand

We can save the conditions in the key-value objects and can be used based on the conditions.

// Longhand
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}

// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();

10. Multi-line String Shorthand

When we are dealing with a multi-line string in code we can do it this way:

//longhand
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
         test test,test test test test`

11.Implicit Return Shorthand

With the use of arrow functions, we can return the value directly without having to write a return statement.

//longhand
function getArea(diameter) {
  return Math.PI * diameter
}
//shorthand
getArea = diameter => (
  Math.PI * diameter;
)

12.Lookup Conditions Shorthand

If we have code to check the type and based on the type need to call different methods we either have the option to use multiple else ifs or go for the switch, but what if we have better shorthand than that?

// Longhand
if (type === 'test1') {
  test1();
}
else if (type === 'test2') {
  test2();
}
else if (type === 'test3') {
  test3();
}
else if (type === 'test4') {
  test4();
} else {
  throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};

var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

13.Object.entries()

This feature helps to convert the object to an array of objects.

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]
**/

14. Object.values()

This is also a new feature introduced in ES8 that performs a similar function to Object.entries(), but without the key part:

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/

15. Repeat a string multiple times

To repeat the same characters again and again we can use the for loop and add them in the same loop but what if we have a shorthand for this?

//longhand 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 
//shorthand 
'test '.repeat(5);

16. Power Shorthand

Shorthand for a Math exponent power function:

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8

17. Numeric Separators

You can now easily separate numbers with just an _ . This will make life of developers working with large numbers more easier.

//old syntax
let number = 98234567

//new syntax
let number = 98_234_567

If you would like to get update yourself with the latest features of JavaScript newest version(ES2021/ES12) check below:

1. replaceAll(): returns a new string with all matches of a pattern replaced by the new replacement word.

2.Promise.any(): It takes an iterable of Promise objects and as one promise fulfills, return a single promise with the value.

3. weakref: This object holds a weak reference to another object without preventing that object from getting garbage-collected.

4. FinalizationRegistry: Lets you request a callback when an object is garbage collected.

5. Private visibility: modifier for methods and accessors: Private methods can be declared with #.

6. Logical Operators: && and || operators.

7. Intl.ListFormat: This object enables language-sensitive list formatting.

8. Intl.DateTimeFormat: This object enables language-sensitive date and time formatting.


Sponsoring 🧑

If you like my work and want to support the like more articals and open-source project's, now you can! Just: Buy Me A Coffee


That's all for this article now.

Hope you like the article. Stay Tuned for more. If really appreciate my work, kindly support me

Thanks for reading!πŸ™

If you liked this article and want more content like this, subscribe to CodeHouse

MΓ‘rio Varela's photo

You are so amazing. I love it. Thank's

Catalin Pit's photo

Great tips and tricks! Loved the article!

Edidiong Asikpo's photo

I learned a lot from this article Sumanth S. I will try out about two of them later today.

Thanks for sharing. πŸ˜€

Babu Suresh's photo

Wow Sumanth S awesome js tips and shortcuts. Very useful article Recommended to read all

Ignacio Vargas's photo

I really liked the way the code explains itself on tip #1. But doing it that way (the clean code way) also helps optimization?

Nice article!