JavaScript Clean Code Manual
1. Use meaningful names
Bad:
const d = new Date();
Good:
const currentDate = new Date();
2. Keep functions small and focused
Bad:
function sendEmailToUser(user) {
// validate email
// format message
// send email
Good:
function isEmailValid(email) { ... }
function formatMessage(user) { ... }
function sendEmail(message, email) { ... }
function sendEmailToUser(user) {
if (!isEmailValid(user.email)) return;
const message = formatMessage(user);
sendEmail(message, user.email);
3. Use constants instead of magic numbers
Bad:
if (user.age > 21) { ... }
JavaScript Clean Code Manual
Good:
const LEGAL_AGE = 21;
if (user.age > LEGAL_AGE) { ... }
4. Use object destructuring
Bad:
function greet(user) {
return `Hello ${user.name}, your age is ${user.age}`;
Good:
function greet({ name, age }) {
return `Hello ${name}, your age is ${age}`;
5. Avoid deep nesting
Bad:
if (user) {
if (user.details) {
if (user.details.address) {
sendMail(user.details.address);
Good:
if (!user?.details?.address) return;
sendMail(user.details.address);
6. Return early to reduce nesting
JavaScript Clean Code Manual
Bad:
function getDiscount(price) {
if (price > 100) {
return price * 0.1;
} else {
return 0;
Good:
function getDiscount(price) {
if (price <= 100) return 0;
return price * 0.1;
7. Avoid redundant comments
Bad:
// Check if the user is an admin
if (user.isAdmin) { ... }
Good:
Code should be self-explanatory. No comment needed here.
8. Use template literals
Bad:
const msg = 'Hello, ' + name + '!';
Good:
const msg = `Hello, ${name}!`;
JavaScript Clean Code Manual
9. Name booleans as questions
Bad:
const visible = true;
Good:
const isVisible = true;
10. Group related data
Bad:
const street = 'Main St';
const city = 'NY';
const zip = '10001';
Good:
const address = { street: 'Main St', city: 'NY', zip: '10001' };