Table of contents
- Use meaningful variable name
- Don’t write "Data” or “Info” at the end of the variables or functions
- Use a variable for a constant value
- Use objects instead of writing lots of variables
- Avoid mental mapping
- Use object destructure to make the code readable
- Use default parameter value
- A function should do only one thing
- Write useful comments
Are you new to JavaScript and want to write better, cleaner code? Clean code is not just about making your code look pretty—it’s about improving readability, maintainability, and collaboration. Whether you’re just starting or aiming to refine your coding skills, following clean code principles will set a solid foundation for your JavaScript journey.
Use meaningful variable name
// bad name
const yyyymmdd = moment().format("YYYY/MM/DD");
const isNotValid = true;
// good name
const currentDate = moment().format("YYYY/MM/DD");
const isValid = true;
In the bad name example, “yyyymmdd” doesn’t make sense. The variable should be meaningful, and the “isNotValid” variable is confusing. In the good name, we can see a good way to make the variable name meaningful and readable.
Don’t write "Data” or “Info” at the end of the variables or functions
// bad name
getUsersData();
getCustomersData();
// good name
getUsers();
getCustomers();
In the bad name example, you can see I have written “data” at the end of the function name which is redundant and doesn’t add any value.
Use a variable for a constant value
// bad way
if(role === 'SUPERADMIN') {
// do something
}
// good way
const SUPERADMIN = 'SUPERADMIN';
if (role === SUPERADMIN ) {
// do something
}
In the bad code example, you can see I have hard coded the ‘SUPERADMIN’ value, which is not a good practice because you may have to use this comparison in many places, and if you ever want to modify the string, you have to do it from everywhere. So, it is better to use a variable like this. Also, I see many people use block letters for constant variable names.
Use objects instead of writing lots of variables
// bad code
const userName = 'Sajib Hossain';
const userAge = 18 // my actual age
// good code
const user = {
name: 'Sajib Hossain',
age: 18 // I am saying the truth, this is my real age :)
}
You can see, In the ‘good code’ the code is much more readable. as we have more data we can add them in the object instead of creating new variables. As a beginner react developer I used to create lots of useState variable but after learning about this pattern I only create 1 state for the form component and update the data.
Avoid mental mapping
// Bad way
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(l => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `l` for again?
dispatch(l);
});
// good way
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(location => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
In the “bad way”, I have written l
variable. it does not convey its purpose or the data it represents. This can confuse developers trying to understand or modify the code. The variable location
indicates that it represents a location, making the code self-explanatory.
Use object destructure to make the code readable
// Array of objects representing locations with additional details
const locations = [
{ name: "Austin", state: "Texas", population: 964254 },
{ name: "New York", state: "New York", population: 8419600 },
{ name: "San Francisco", state: "California", population: 815201 },
];
// not so good way
locations.forEach((location) => {
console.log(`Location: ${location.name}`);
console.log(`State: ${location.state}`);
console.log(`Population: ${location.population}`);
console.log("-----");
});
// good way
locations.forEach((location) => {
const { name, state, population } = location;
console.log(`Location: ${name}`);
console.log(`State: ${state}`);
console.log(`Population: ${population}`);
console.log("-----");
});
In the “not-so-good way “, I have not used object destructuring, so I have to use repetitive dot notation. Object destructuring allows us to unpack specific properties from objects into variables. This eliminates the need for repetitive dot notation (e.g., location.name
, location.state
) and makes our code more concise and easier to understand.
Use default parameter value
// not so good way
function greetUser(name) {
const userName = name || 'guest';
console.log(`Hello, ${name}! Welcome to our platform.`);
}
// good way
function greetUser(name = "Guest") {
console.log(`Hello, ${name}! Welcome to our platform.`);
}
greetUser("Alice");
greetUser();
In the “Not so good way,” I have not given any default value, so I have to create a variable for this if the name is not provided. Meanwhile, in the “good way,” I have a default value that takes care of it and is much more readable.
A function should do only one thing
// bad code
function createAndSendEmail(recipient, subject, content) {
const emailBody = `
To: ${recipient}
Subject: ${subject}
${content}
`;
// Simulate sending the email
console.log(`Sending email: \n${emailBody}`);
}
// good code
function createEmailBody(recipient, subject, content) {
return `
To: ${recipient}
Subject: ${subject}
${content}
`;
}
function sendEmail(emailBody) {
console.log(`Sending email: \n${emailBody}`);
}
// Example Usage
const recipient = "example@example.com";
const subject = "Welcome to Our Service";
const content = "Thank you for signing up! We are excited to have you.";
const emailBody = createEmailBody(recipient, subject, content);
sendEmail(emailBody);
In the bad code example, we have a single function that creates the email body and sends it. Which makes the function long and will be hard to debug in the future if more things are added. Now we can separate the logic and create 2 functions, one for creating the email body and another for sending the email.
Write useful comments
// bad comments
// calculate total price
function calculateTotalPrice(cart) {
let total = 0;
cart.forEach(item => {
total += item.price * item.quantity; // calculating total price
});
return total; // returning total price
}
// good comments
/**
* Calculates the total price of items in a cart.
*
* @param {Array} cart - An array of objects representing items in the cart.
* Each object should have the properties:
* - price: The price of the item (number).
* - quantity: The quantity of the item (number).
*
* @returns {number} The total price of all items in the cart.
*/
function calculateTotalPrice(cart) {
let total = 0;
cart.forEach(item => {
total += item.price * item.quantity;
});
return total;
}
const cartItems = [
{ price: 20, quantity: 2 },
{ price: 10, quantity: 3 },
];
console.log(calculateTotalPrice(cartItems));
In the “bad comments” code you can see the comments have little meaning. but in the “good comments” code, you can see what the function is doing. so it is crucial to write good comments.
Thank you for reading this far. I hope this article helps you become a better developer. I learned these patterns and rules from a GitHub repository. If you want to learn about more advanced patterns, you can also explore this repo. Let me know if you have any feedback. Best of luck.