Forem

Cover image for 16 Essential JavaScript Best Practices for Smarter Coding
Shihab Haque
Shihab Haque

Posted on

16 Essential JavaScript Best Practices for Smarter Coding

JavaScript is the language of the web. Nowadays, we often use frameworks and libraries for our day-to-day web application building, but still, it is quite effective to learn the best practices of JavaScript to write more effective and efficient code. Here I have discussed the top 20 best practices that I think are a must-know for all the web programmers.

1. Always declare variables outside of a 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 practice. 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
cosnt myDiv=document.querySelector('.my-div');
const len = 10000
for(let i = 0;i<len;i++){
    //other operations
};
Enter fullscreen mode Exit fullscreen mode

2. Try not to include multiple complex operations inside a single function.

One single function may contain several complex operations and execute them in a single runtime. But that is not a best practice, as sometimes the code becomes hard to comprehend and debug. Although it has nothing to do with performance, instead the code is much easier to read. It is also simple to debug, and other programmers can simply comprehend and modify our code. Developers love to call it "refactoring," as 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);
};
Enter fullscreen mode Exit fullscreen mode

3. Use let and const instead of var

var is global scoped or function-scoped, meaning it is outside of the function in which it is declared. let and const are blocked-scoped. let and const prevent accidental modifications from outside of a scope.
in code we can see,

//var
function example() {
    if (true) {
        var x = 10;
    }
    console.log(x); // 10 (unexpected behavior, since x is accessible outside the block)
}
example();

//let or const
function example() {
    if (true) {
        let y = 20;
    }
    console.log(y); // ReferenceError: y is not defined
}
example();

Enter fullscreen mode Exit fullscreen mode

Using let or const instead of var avoids hoisting issues and prevents unexpected behaviors from coming. In 2025, no one uses var. But knowing var is important to understand some fundamental JavaScript concepts like hoising and scoping.
Another key thing to remember is that we may get confused while choosing between const and let. So my suggestion is to use const always, and whenever you need to change the variable, then use let.

//❌ bad practice
var name = 'alice'
var name = 'bob' //you can do this

//✅ best practice
let name = 'alice'
name = 'bob'

const color = 'cyan'
Enter fullscreen mode Exit fullscreen mode

4. Use one variable to define multiple values

Instead of declaring each variable with let or const, we can declare the variable key once and assign multiple variables separated by commas. Although commas are not mandatory. Editor adds commas by default while saving the file.

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

5. Use Arrow functions

Using arrow functions (=>) in JavaScript is often a best practice. Using arrow function makes the code concise and readable, and it is ideal for callback functions like the expressJS code you write when your client hits a particular route.

//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;

Enter fullscreen mode Exit fullscreen mode

NOTE: In some specific cases, using the arrow function is not recommended. for instance,

  • Arrow function doesn’t bother about this keyword. when we are using it as an object method, this does not refer to the object itself. for this using arrow functions is not recommended here.
const user = {
    name: "alice",
    greet: () => {
        console.log(`Hello, ${this.name}`); // `this` is the window object
    }
};

user.greet(); // Hello, undefined
Enter fullscreen mode Exit fullscreen mode
  • Arrow functions cannot be used as constructors as it cannot be assigned with the new keyword.
const Person = (name) => {
    this.name = name;
};

const p = new Person("Sayma"); // TypeError: Person is not a constructor
Enter fullscreen mode Exit fullscreen mode

6. Use spread operator

It is a common best practice to use spread operator (...) when working with arrays, objects and function arguments. Makes it easier to work with arrays and objects when copying or merging. Also, it replaces the methods like concat(), slice() and apply() that makes the code cleaner and more readable.

//❌ bad practice
const newNumbers = numbers;
newNumbers.push(4);
console.log(numbers); // [1, 2, 3, 4] (Oops! Original array changed)

//✅ best practice
const numbers = [1, 2, 3];
const newNumbers = [...numbers]; // Creates a copy
newNumbers.push(4);

console.log(numbers); // [1, 2, 3] (Original array remains unchanged)
console.log(newNumbers); // [1, 2, 3, 4]

//for objects
const user = { name: "Sayma", age: 20 };
const updatedUser = { ...user, age: 21, country: "Bangladesh" };

console.log(updatedUser); // { name: "Sayma", age: 21, country: "Bangladesh" }
Enter fullscreen mode Exit fullscreen mode

7. Write meaningful comments

Comments are an essential part of writing readable, maintainable, and understandable code. Writing meaningful comments gives purpose to the code you are writing. However, There are some key things to know while writing comments like,

  • Use Comments to Explain “Why,” Not “What” The code should be clear enough to explain "what" and a comment whould explain the "why" of that code.
// ❌ Bad Comment: Redundant
const result = calculateTax(income);
// This function calculates the tax

// ✅ Good Comment: Explains the 'why'
const result = calculateTax(income);
// Calculate tax because the tax rate changes every year
Enter fullscreen mode Exit fullscreen mode

8. Use Template Literals (`)

the key located below the Esc key of your keyboard is the template literal. Template literals are a modern and preferred way of working with strings in JavaScript. using them makes the code more readable, cleaner and maintainable. In fact, before this, multi-line strings were harder to

//❌ Error
console.log("I cannnot be written in
multiple line because I am not a template literal")

//✅ OK
console.log(`I can be written in
multiple line because I am inside template literal`)

//❌ Bad practice
let age = 11+1

let name= "alice"

console.log(name + " is now " + age + " years old.")

//✅ Best practice

let name = "alice"

console.log(`${name} is now ${11 + 1} years old`)
Enter fullscreen mode Exit fullscreen mode

9. Use Strong type checking(===)

There are two types of operand type checking (== & ===) in JavaScript. The Double Equals(==) simply compares the values of two operands. Whereas The Tripple Equals(===) compares values and data types between two operands. It is highly recommended to use strong type Tripple Equal checking(===). In fact, In modern frameworks and libraries like React or Angular, we mostly(99%) use (===)

// example:
4 == "4" //true
4 === "4" //false

// Bad practice
let a = "600"

if (a == 600) {
    //reachable
}

// Best practice
if (a === 600) {
    // not reachable
}
Enter fullscreen mode Exit fullscreen mode

Note: Use == if you are aware of what you are doing.

10. Don't pollute the global prototype

The prototype is an object that is associated with every function and object by default in JavaScript.

Making any changes to the prototype is called "Prototype Pollution.". Avoiding making any changes to the prototype is good practice. Some developers may think that they are cool with changing the prototype, but because of this, the expected behavior of javascript may get changed.

// Bad practice
String.prototype.changeString= () =>{
    // implementing a random function
}

// Best practice
class changeString extends String{
    newFunction(){
        //implementation
    }
}

let randomName = new changeString('some parameter')

Enter fullscreen mode Exit fullscreen mode

11. Declare default parameter to function arguments

One of the cool ES6 features is the default parameter. This technique ensures that functions can handle cases where arguments may not be passed without causing errors or requiring extra logic to check if arguments exist.
If a function in JavaScript is called with missing arguments (less than declared), the missing values are set to undefined. Instead, we can assigne default values.

//❌ Bad practice / Old way
function drink(beverage) {
    beverage = beverage !== undefined ? beverage : "PEPSI";
    return beverage
}
console.log(drink()) //PEPSI

//✅ Best practice / ES6 way
function drink(beverage = "PEPSI") {
    return beverage
}

console.log(drink()) //PEPSI
Enter fullscreen mode Exit fullscreen mode

12. Give a Meaningful variable and function name

This one is self-explanatory. Each variable and function should contain the purpose behind assigning it. Giving clean variable names though they are large is a good practice.

//❌ Bad practice
const list1 = ["bread", "butter", "jam"]
const list2 = ["monkey", "lion", "cow"]

function LoginPage(){
    //implement
}

//✅ Best Practice
const shoppingList = ["bread", "butter", "jam"]
const animalList = ["monkey", "lion", "cow"]

function totalLoginAttemptsInPage(){
    //implement
}
Enter fullscreen mode Exit fullscreen mode

13. Know the falsy values

There are several values in JavaScript that are considered falsy. Knowing them will give an understanding about how the boolean formats of JavaScript work.
the falsy values are false, 0, "", null, undefined, NaN

if (!false && !0 && !null && !"" && !null && !undefined && !NaN) {
  console.log('these are falsy');
}
Enter fullscreen mode Exit fullscreen mode

NOTE: In javascript empty objects({}) and empty arrays([]) are considered truthy

14. Quickly Assign Variable Values With Destructuring

It is also another a common best practice to follow. Destructuring is widely used with libraries like React. It makes writing the code smooth, clean and readable.

// Extracting
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;

const person = { name: 'John', age: 25 };
const { name, age } = person;

console.log(firstColor);  // red
console.log(age); // 25

//function parameters
function greet({ name, age }) {
  console.log(`${name} is ${age} years old.`);
}
greet({ name: 'alice', age: 22 });
Enter fullscreen mode Exit fullscreen mode

15. Use Async/Await

Using async/await is considered a best practice in modern JavaScript. In the places of asynchronous operations like API calls, reading files or promise resolve, this syntatic sugar code makes it look and behave more like synchronous code. It improves readability, Error handling becomes smoother and avoids "Callback Hell". It is also better for debugging.

// Without async/await
fetchData()
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

//✅ With async/await
async function getData() {
  try {
    const res = await fetchData();
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

16. avoid eval()

If you are new to JavaScript and don't know anything about eval(), It is best to avoid it altogether in any scenario.

Conclusion

I hope you find these tips helpful and you'll keep them in mind when you code in JavaScript. If you have any additional tips or best practices, feel free to share them in the comments. Let's keep learning and improving together!

My Socials:
LinkedIn
Twitter

Top comments (0)