JavaScript: Top 10 Best Practices of 2023

JavaScript: Top 10 Best Practices of 2023

Best practices are related to performance. Here are the 10 best practices for JavaScript. I try to use them daily. Let's see how we can write the best code using these best practices.

1:Always declare variables outside of the for loop.

If we declare a variable inside of our for loop, it will be assigned constantly until the for loop is finished. The performance of that code degrades as the application grows larger. This is not a good method. It is an indication of uneven development.

/// Bad Practice

for(let i = 0;i<10000;i++){
    let myDiv=document.querySelector('.my-div');
    //other operations
};

/// Best Practice

let myDiv=document.querySelector('.my-div');
let len = 10000
for(let i = 0;i<len;i++){
    //other operations
};

2:Try not to use multiple works inside one function

One function shouldn't have several operations. Instead, we can divide the operation into several functions and execute them one at a time.

Although it has nothing to do with performance, that code is much easier to read. It is also simple to debug. Other programmers can simply comprehend and modify our code. Developers love to call it "refactoring." because it is a part of refactoring.

/// Bad practice

function callThem(memberArr){
    memberArr.forEach(person=>{
        const isValid= allUserObj.find(person.name);
        if(isValid){
            call(person);
        };
    })
};
/// Best practice
function isValidMember(member){
    const isValid= allUserObj.find(member.name);
    return isValid;
};
function callThem(users){
    users.filter(isValidMember).forEach(call);
};

3:Using conditional shorthand

It is not necessary to use booleans to determine whether a property is true or false. The code below tells more:

/// Bad practice
if(myName === true){
    //.....
};

if(myName === false){
    //.....
};

/// Best practice
if(myName){
    //.....
};

if(!myName){
    //.....
};

4:Use let and const instead of var

Var is global scope, and let or const is blocked scope. var can sometimes produce unexpected results. To avoid this, always try to use let or const.

/// Bad practice
var myName = "Adnan";

//Best practice

let myName = "Adnan";

const myName = "Adnan";

5:Use one variable to define multiple values

Instead of declaring each variable with let/var/const, we can declare the variable key once and assign multiple variables separated by commas. A tough comma is not mandatory.

/// Bad
const container = document.querySelector('.container');
const navBar = document.querySelector('.nav-bar');
const myDiv = document.querySelector('.my-div');

/// Best
const container = document.querySelector('.container'),
    navBar = document.querySelector('.nav-bar'),
    myDiv = document.querySelector('.my-div');

6:Use Arrow function

One of the most useful modern ES6 features are the Arrow functions. But before using the Arrow function, we need to know that:

  • arrow function doesn’t bother about "this" keyword.

  • new keyword doesn’t work on arrow function.

//example:
let number= ()=>{
    return 10
};
console.log(number()); //10

//if function has only one statement
let number = ()=> 10; //(return omited for one line also you cannot write return)

// if has one parameter
let number = n => n;

Do you want to know more about Arrow functions?

Check out this notion slide: Click here

7:Use spread operator

The spread operator is used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

//normal
var numbers = [1, 2, 3];

let newNumbers=[...numbers,4,5,6];

console.log(newNumbers); //[ 1, 2, 3, 4, 5, 6]

//making exact copy

let a = [...numbers]; //making exact copy

numbers.push(8,9,10);

console.log(numbers); //[ 1, 2, 3, 8, 9, 10]
console.log(a); // [1, 2, 3]

// it also work as concat method
//object spreading

let obj1={
    name: 'ferrari',
    color: 'red'
}
let obj2={
    founder: 'Enzo ferrarri',
    favdriver: 'Micheal Schumacher'
}

let about ={
    ...obj1,
    ...obj2
}

8:Use IIFE as much as possible

IIFE stands for "Immediately Invoked Function Expression." This function is invoked by itself. There is no need for an extra line of code to call it.

    // normal
    function replyMe() {
        let text = "this is a reply text";
        return text
    }
    replyMe();

    // IIFE
    (function replyMe() {
        let text = "this is a reply text";
        return text
    })();

9:Give meaningful comments

JavaScript comments can be used to explain JavaScript code and make it more readable. JavaScript comments can also be used to prevent execution when testing alternative code.

Additionally, comments are in HTML and CSS too. Always try to comment in a meaningful way.

// This is JavaScript comment

<!-- this is html comment -->

/* This is css comment */

10:Use semicolons

This is the most underrated but one of the most crucial best practice of JavaScript. Although JavaScript is intelligent enough to detect the use of semicolons, I strongly advise using them.

Developers who work at the enterprise level know it. Sometimes, a large amount of damage occurs just because of a semicolon.

// Bad practice
const variable = "I am assigned"

function msg(){
    return `I am a message`
}
// Best practice
const variable = "I am assigned";

function msg(){
    return `I am a message`;
}

Last words

Thanks for reaching out this far. I just started blogging, and most of my blogs are not viewed that much. But if you are here, I highly respect you.

I am Adnan Saim. a frontend developer and freelancer. You can definitely connect with me on:

Twitter linkedin github

If this blog gets 10 likes, I will consider releasing part 2.