JavaScript Best Practices
In this article, you will learn about the best practices in JavaScript, which are essential for writing efficient and maintainable code. These guidelines help both beginners and experienced developers create cleaner, optimized, and less error-prone JavaScript.
Table of Contents
- Use “const” and “let” Instead of “var”
- Use “===” Instead of “==”
- Minimize The Use of Global Variables
- Declarations on Top
- Use Arrow Functions Where Appropriate
- Use Template Literals
- Use Destructuring for Arrays and Objects
- Keep Functions Small and Focused
- Declare Objects and Arrays with const
- Don’t Use new Object()
- Use Parameter Defaults
- Avoid long argument list
- End Your Switches with Defaults
- Use Optional Chaining
- Optimize Performance: Avoid Repeated DOM Manipulation
- Handle Errors Gracefully
- Document Your Code
1. Use “const” and “let” Instead of “var”
The var keyword in JavaScript has function-level scoping, which can lead to unexpected behavior, especially in larger codebases.
Instead, use let and const, which offer block-level scoping and prevent issues like variable hoisting.
const MAX_USERS = 10; // Value cannot be reassigned
let userCount = 0; // Value can be changed
2. Use “===” Instead of “==”
The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type.
console.log(1 == '1'); // true (loose equality with coercion)
console.log(1 === '1'); // false (strict equality without coercion)
3. Minimize The Use of Global Variables
Global variables can lead to code that is difficult to debug and maintain, as they can be modified from anywhere in your codebase.
Global variables and functions can be overwritten by other scripts.
4. Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function.
Example without declarations on top (poor practice):
function calculateTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
let discount = 0.1; // Declare variables late
let discountedTotal = total - total * discount;
return discountedTotal;
}
Example with declarations on top (best practice):
function calculateTotal(items) {
let total = 0;
let discount = 0.1; // All variables declared at the top
let discountedTotal;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
discountedTotal = total - total * discount;
return discountedTotal;
}
5. Use Arrow Functions Where Appropriate
Arrow functions provide a cleaner, shorter syntax for writing functions.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
6. Use Template Literals
Template Literals use back-ticks rather than the quotes (“”) to define a string:
let text = `Hello World!`;
With template literals, you can use both single and double quotes inside a string:
let text = `He's often called "Johnny"`;
Template literals allow variables in strings:
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
7. Use Destructuring for Arrays and Objects
Destructuring allows you to unpack values from arrays or properties from objects into variables, making your code more concise and readable.
// Array destructuring
const [x, y] = [10, 20];
// Object destructuring
const user = { name: 'Alice', age: 25 };
const { name, age } = user;
8. Keep Functions Small and Focused
A best practice in any programming language is to keep your functions small and focused on a single task.
// Good: function that focuses on one task
function calculateTotalPrice(price, tax) {
return price + price * tax;
}
9. Declare Objects and Arrays with const
Declaring Objects and arrays with const will prevent any accidental change of type.
// Declaring an array with const
const fruits = ['apple', 'banana', 'orange'];
// You can modify elements inside the array
fruits.push('grape'); // Valid
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']
// But you cannot reassign the entire array
// fruits = ['pineapple']; // Error: Assignment to constant variable
// Declaring an object with const
const car = {
brand: 'Toyota',
model: 'Corolla'
};
// You can modify properties of the object
car.model = 'Camry'; // Valid
console.log(car); // { brand: 'Toyota', model: 'Camry' }
// But you cannot reassign the entire object
// car = { brand: 'Honda', model: 'Civic' }; // Error: Assignment to constant variable
10. Don’t Use new Object()
- Use “” instead of new String()
- Use 0 (zero) instead of new Number()
- Use false instead of new Boolean()
- Use {} instead of new Object()
- Use [] instead of new Array()
- Use /()/ instead of new RegExp()
- Use function (){} instead of new Function()
11. Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments.
Here’s a short example of best practice using parameter defaults:
// Function with default parameter values
function greet(name = 'Guest', greeting = 'Hello') {
console.log(`${greeting}, ${name}!`);
}
// If no arguments are passed, the default values will be used
greet(); // Output: "Hello, Guest!"
// If arguments are passed, the default values are overridden
greet('Alice'); // Output: "Hello, Alice!"
greet('Bob', 'Hi'); // Output: "Hi, Bob!"
12. Avoid long argument list
Use a single object parameter and destructuring assignment instead. It also makes handling optional parameters much easier.
function getRegisteredUsers ({ fields, include, fromDate, toDate }) {
/* implementation */
}
getRegisteredUsers({
fields: ['firstName', 'lastName', 'email'],
include: ['invitedUsers'],
fromDate: '2024-09-24',
toDate: '2024-12-24'
})
13. End Your Switches with Defaults
Always end your switch statements with a default. Even if you think there is no need for it.
Here’s a short example of this best practice:
function getDayName(dayNumber) {
switch (dayNumber) {
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
case 7:
return 'Sunday';
default:
return 'Invalid day'; // Default case handles unexpected input
}
}
console.log(getDayName(3)); // Output: 'Wednesday'
console.log(getDayName(10)); // Output: 'Invalid day'
14. Use Optional Chaining
The optional chaining (?.) operator stops the evaluation if the value before ?. is undefined or null, and returns undefined.
The “non-existing property” problem:
let user = {}; // a user without "address" property
alert(user.address.street); // Error!
Here’s the safe way to access user.address.street using ?. :
let user = {}; // user has no address
alert( user?.address?.street ); // undefined (no error)
15. Optimize Performance: Avoid Repeated DOM Manipulation
Direct DOM manipulation is costly in terms of performance. If you need to make multiple updates, batch changes together to reduce reflows and repaints.
Use DocumentFragment or libraries like React or Vue, which optimize DOM rendering efficiently by using virtual DOM techniques.
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
fragment.appendChild(div);
}
document.body.appendChild(fragment);
16. Handle Errors Gracefully
Error handling is critical in JavaScript. Use try/catch blocks for asynchronous code or parts of your application that might fail, and provide meaningful error messages to help with debugging.
try {
let result = riskyOperation();
} catch (error) {
console.error('An error occurred:', error.message);
}
17. Document Your Code
Readable code should always be documented. Use comments to explain the purpose of functions, clarify complex logic, or describe edge cases.
Well-documented code helps both current and future developers understand the code faster and with less frustration.
/**
* Calculate total price with tax.
* @param {number} price - The base price of the product.
* @param {number} tax - The tax percentage (e.g., 0.2 for 20%).
* @return {number} Total price including tax.
*/
function calculateTotalPrice(price, tax) {
return price + price * tax;
}
Conclusion
Adhering to JavaScript best practices leads to more maintainable, readable, and efficient code. Whether you’re a beginner or an experienced developer, keeping these tips in mind will make your code more professional and easier to debug and optimize.