How to Write Clean JavaScript code
2 min readOct 23, 2021

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
- Writing clean code is nothing but code easier to read, modify, and refactor for people other than the original programmer.
- The code should be easy to read, whether that reader is the original author of the code or somebody else. There shouldn’t be any doubts and misunderstandings.
- Things such as application flow, the purpose of each function/class/variable/expression, and how different objects collaborate should be clear.
- Writing clean code has the following advantages,
Lower maintenance burden
Code consistency across the team
Improves code readability
Tips for writing clean code
- Use meaningful names for variables, functions, and objects.
// Don't
let a = 'kamesh sethupathi';
let b = 'kamesh.sethupathi@domain.ext';function printIt() {
console.log('Name', a);
console.log('Email', b);
}
// Do
let name = 'kamesh sethupathi';
let email = 'kamesh.sethupathi@domain.ext';function printUserInfo() {
console.log('Name', name);
console.log('Email', email);
}
- Avoid adding unnecessary context. Like
user.userID
,image.isValidImage()
. It can be simplified likeuser.ID
,image.isValid()
. - Never hardcode any values. Always use constants for that purpose.
// Don't
setInterval(pingServer, 10 * 1000);
// Do
const SERVER_PING_INTERVAL = 10 * 1000; // const filesetInterval(pingServer, SERVER_PING_INTERVAL);
- Use default values for arguments
// Don't
function printAllFilesInDirectory(dir) {
const directory = dir || "./";
// ...
}
// Do
function printAllFilesInDirectory(dir = "./") {
// ...
}
- Only comment business logic
- Favor object literals or maps over switch statements / If-else ladder.
// Don't
if(user == 'admin') {
console.log('You have full potential');
} else if( user == 'editor') {
console.log('You can publish, review, and access the page');
} else if( user == 'author') {
console.log('You can publish and access the page');
}
// Do
let permissions = {
admin: 'You have full potential',
editor: 'You can publish, review, and access the page',
author: 'You can publish and access the page'
};console.log( permissions[user] );
- Use shorthands whenever possible
- Use non-negative conditionals. Like prefer
isValidUser
overisNotValidUser()
. - Do not repeat yourself ( DRY )
// Don't
function addTwoNumbers(a, b) {
console.log(a + b);
}function addThreeNumbers(a, b, c) {
console.log(a + b + c);
}
// Do
function addNumbers(...args) {
console.log( args.reduce((prev, cur)=> prev+cur,0) );
}
- Avoid using flags as arguments. Like having
isPublished
as an argument. - Avoid executing multiple actions in a function. A function should do one action that is intended for.