DEV Community

Cover image for 17 Javascript optimization tips to know in 2021 🚀
Blessing Hirwa
Blessing Hirwa

Posted on • Updated on

17 Javascript optimization tips to know in 2021 🚀

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.

After one of my articles about 8 neat javascript skills you didn't know in 4 minutes, here I am coming with a new series to cover shorthand techniques that help you to write more clean and optimized JavaScript Code.My motive is to introduce all the JavaScript best practices such as shorthand and features which we must know as a frontend developer to make our life easier in 2021.This is a Cheat list for JavaScript Coding you must know in 2021.

1. If with multiple conditions

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

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
Enter fullscreen mode Exit fullscreen mode

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.

// Longhand
let test= boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
console.log(test);
Enter fullscreen mode Exit fullscreen mode

After nesting the condition we remain with something which looks like this:

let x = 300,
let test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
Enter fullscreen mode Exit fullscreen mode

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|| '';
Enter fullscreen mode Exit fullscreen mode

4. Null Value checks and Assigning Default Value

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

5. Undefined Value checks and Assigning Default Value

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

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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)();
Enter fullscreen mode Exit fullscreen mode

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]();
Enter fullscreen mode Exit fullscreen mode

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`
Enter fullscreen mode Exit fullscreen mode

11.Implicit Return Shorthand

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

Longhand:
//longhand
function getArea(diameter) {
  return Math.PI * diameter
}
//shorthand
getArea = diameter => (
  Math.PI * diameter;
)
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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' ]
]
**/
Enter fullscreen mode Exit fullscreen mode

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']
**/
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

16. Power Shorthand

Shorthand for a Math exponent power function:

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Conclusion
What's more, there we have it. 17 ways to optimize your code with modern JavaScript techniques.

👋Let's be friends! Follow me on Twitter and instagram for more related content. Don't forget to follow me also here on Dev as well to get updated for new content.

Stay safe 🏠

Top comments (52)

Collapse
 
estruyf profile image
Elio Struyf

Great list, just one thing in tip number 6 foreach Loop Shorthand. A for...in is not the same as a for...of loop!

With the for...in you iterate over the object its properties. For the for...in with an array, you'll get the index value.

With the for...of you iterate over all elements inside the array, so i will be the element and not the index.

Collapse
 
bugmagnet profile image
Bruce Axtens

Thanks for pointing that out, @estruyf . The following deno session demonstrates

> const b = "abcdef".split("")
undefined
> b
[ "a", "b", "c", "d", "e", "f" ]
> for (let x in b) console.log(x)
0
1
2
3
4
5
undefined
> for (let x of b) console.log(x)
a
b
c
d
e
f
undefined
Enter fullscreen mode Exit fullscreen mode
Collapse
 
denisdiachenko profile image
DenisDiachenko

That's a good list, just one thing I would like to mention in tips 4 and 5. It's better to check if the value is null or undefined using Nullish Coalescing Operator (??) since for some cases it might be an unexpected behavior:

const foo = null || 42;
console.log(foo);
// expected output: 42
Enter fullscreen mode Exit fullscreen mode
const foo = 0 || 42;
console.log(foo);
// expected output: 0, but will be 42
Enter fullscreen mode Exit fullscreen mode

So, in that case ?? will work as expected

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0 and will be 0
Enter fullscreen mode Exit fullscreen mode

Thank you for your work!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

In some cases Nullish Coalescing Operator is the best choice. Thanks for the assistance.

Collapse
 
andrewbridge profile image
Andrew Bridge

There are some good tips here! I hadn't come across the numeric separators, and it's great to see a replaceAll method after years of having to reach for a regex for that simple task!

One thing I'd note is being careful with falsey checks, in #3 your Longhand version would allow any value other than those you've specified. The Shorthand version would also fail the value 0 and false. If you're working with numbers, that can cause tricky to find bugs later on.

The other bit may be more of a preference but nested ternary statements or function calls via a ternary (as in #8) are quite hard to read compared to the "long" alternative and that could make it far more susceptible to bugs and harder to find it when it comes up. I'd far prefer 5 clear lines of code and let my minifier convert it to a one liner before I push my code live!

Anyway, great list! Thanks!

Collapse
 
jafuentest profile image
Juan A. Fuentest Torcat

+1 I would advise to not nest two or more ternary operations. Also avoid it entirely if it means you'll get a single like 100+ characters long, or 120 depending on preference. But more than that usually means your code will be hard to read

Collapse
 
hiasltiasl profile image
Matthias Perktold

When I have nested ternaries, I format them this way:

ˋˋˋjavascript
let test2 = (x > 100) ? 'greater 100'
: (x < 50) ? 'less 50'
: 'between 50 and 100';
ˋˋˋ

IMHO this reads quite nicely, since every condition is paired with the corresponding result, similar to a ˋswitchˋ block or an if-elseif-else chain.

Still, you shouldn‘t push it too far. When the conditions or value expressions get long, this becomes unreadable as well.

Thread Thread
 
andrewbridge profile image
Andrew Bridge • Edited

I agree, it reads nicely enough, but what's the benefit to this over:

let test2 = 'between 50 and 100';
if (x > 100) { test2 = 'greater 100'; }
else if (x < 50) { test2 = 'less 50'; }
Enter fullscreen mode Exit fullscreen mode

It's dealers choice with regard to using an else statement or default assignment as above and the formatting isn't my cup of tea, but it's still nevertheless the same statement on three lines. IMO, this is still way clearer and I don't see any downside to it.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Long chained tenary operators are not good.

Collapse
 
flyingcrp profile image
flyingCrp

nice~
The code is used by the machine,and another function is to show it to people .
We have to make some trade-offs

Collapse
 
kpmcdowellmo profile image
Keven McDowell

This list contains some good tips. Using an object in place of a switch statement is one of my favorite tricks to use. For your first tip, you may want to also consider using an object, since Array.includes is at worst a O(n) operation compared to an object lookup, which is a O(1) operation.

Collapse
 
ufocoder profile image
Sergey Ivanov • Edited

Code from the article, the second example:

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
Enter fullscreen mode Exit fullscreen mode

It could be shorter, like the following:

let test = x > 10;
Enter fullscreen mode Exit fullscreen mode

It could be not easy to read or understand several ternary operators in one and the same statement sometimes

Shorter not means better!

Collapse
 
shadowtime2000 profile image
shadowtime2000

When I hear optimization I think making the file size smaller and having the code run faster, not refactors that make the code a lot cleaner.

Collapse
 
z2lai profile image
z2lai

True, this title definitely needs to be renamed to Clean Code tips as it's quite helpful.

Collapse
 
ctrlsquid profile image
zach

These tips are really good.

Generally, I feel that using switch statements is most of the time not necessary, and using an object is very much a good alternative and one that is commonly available.

That being said, I think number 9 is misleading. You stated that objects are shorthand for switch statements, and they aren't. They're an alternative you could do sometimes. But saying an object is "shorthand" for a switch statement is definitely not correct.
There are definitely situations where you would need a switch statement instead of an object (IE, the object cannot replace the switch statement). A shorthand of syntax should be able to replace the original in all situations.

I think just modifying the text to state that its not a shorthand but an alternative that's commonly available would be good.

Collapse
 
fadhilijosue profile image
FADHILI Josue • Edited

this is for making clear the use of for...in and for...of

In JavaScript, for...in and for...of are both loop constructs used to iterate over data structures, but they are used for different purposes and work with different types of collections.

for...in:
The for...in loop is used to iterate over the properties of an object. It works with enumerable properties, which include both own properties and inherited properties from the object's prototype chain.

for (variable in object) {
// code to be executed
}

Usage:
`const person = {
name: 'fadhili',
age: 30,
city: ''rwanda
};

for (let key in person) {
console.log(key + ': ' + person[key]);
}
// that will loop in object keys(name, age, city)
//it will output object key: object value`

for...of:
The for...of loop is used to iterate over the elements of an iterable object. Iterable objects include arrays, strings, sets, maps, and other data structures that have a defined iteration protocol.

for (variable of iterable) {
// code to be executed
}

Usage:

`const colors = ['red', 'green', 'blue'];

for (let color of colors) {
console.log(color);
}
//In this example, for...of is used to loop through the elements ('red', 'green', 'blue') of the colors array.`

Key Differences:

1. Iterating Over:

for...in: Iterates over object properties.
for...of: Iterates over iterable values (e.g., elements in an array).

2. Iteration Variables:

for...in: Iterates over property names (keys).
for...of: Iterates over values.

3. Suitable for:

for...in: Best used for objects and when you need to enumerate object properties.
for...of: Best used for iterating over iterable collections like arrays and strings.

4. Works With:

for...in: Works with objects, including their inherited properties.
for...of: Works with iterables, including arrays, strings, sets, maps, etc.

5. Order of Iteration:

for...in: The order of iteration is not guaranteed and may vary between JavaScript engines.
for...of: Iterates in the order the elements appear in the collection.

6. Compatibility:

for...in: Supported in all modern browsers and older versions of JavaScript.
for...of: Introduced in ES6 and may not be supported in older browsers without

7. transpilation.
Remember to use for...in when you need to iterate over object properties and for...of when you're working with iterable collections like arrays or strings.

Collapse
 
jupiteris profile image
Jupiter Programmer

real experience!!!

Collapse
 
ram12ka4 profile image
Ram Kumar Basak

I am getting " Uncaught SyntaxError: expected expression, got keyword 'throw' " error while declaring this statement (!func) && throw new Error('Invalid value ' + type);

Collapse
 
blessinghirwa profile image
Blessing Hirwa

which trick were you trying?

Collapse
 
ram12ka4 profile image
Ram Kumar Basak

I just type code you mentioned on console and got this error

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

which code? On which trick number?

Thread Thread
 
ram12ka4 profile image
Ram Kumar Basak

I typed the code of point no 12 on console

Collapse
 
marcelcruz profile image
Marcel Cruz

Those are great tips, and they improve readability a lot. Thanks for sharing!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Glad to hear that.

Collapse
 
stackerine profile image
Stackerine

In the part 13.Object.entries()
Object.entries returns an array of array and not an array of object as mentioned.

Good job!

Collapse
 
pitops profile image
Petros Kyriakou

Good list but please don't use this

(!func) && throw new Error('Invalid value ' + type); func();

it's unreadable when you scan the code

Collapse
 
aboudard profile image
Alain Boudard

Great list of tips !
About arrow function, if I'm not wrong, you can lose the paranthesis (these should be brackets no ?) here :

//shorthand
getArea = diameter => Math.PI * diameter;

Collapse
 
blessinghirwa profile image
Blessing Hirwa

That's also correct. I just wanted everyone to spot the difference between the tow functions.

Collapse
 
gershomlapaix profile image
Nsengiyumva Gershom La paix

Thank you @blessing
Great work!!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Thanks mate.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.