Clean code is easy to read, understand, and modify.
Meaningful Names#
1// ❌ Bad
2const d = new Date();
3const u = users.filter(u => u.a > 18);
4
5// ✅ Good
6const currentDate = new Date();
7const adultUsers = users.filter(user => user.age > 18);Use Searchable Names#
1// ❌ Bad
2setTimeout(callback, 86400000);
3
4// ✅ Good
5const MILLISECONDS_PER_DAY = 86400000;
6setTimeout(callback, MILLISECONDS_PER_DAY);Small Functions#
1// ❌ Bad: Function doing too much
2function processOrder(order: Order) {
3 // 100+ lines doing validation, calculation, payment, email
4}
5
6// ✅ Good: Single responsibility
7function processOrder(order: Order) {
8 validateOrder(order);
9 const total = calculateTotal(order);
10 processPayment(order, total);
11 sendConfirmation(order);
12}Limit Parameters#
1// ❌ Bad
2function createUser(name, email, age, address, phone) {}
3
4// ✅ Good
5interface CreateUserData {
6 name: string;
7 email: string;
8 age?: number;
9}
10function createUser(data: CreateUserData) {}Avoid Side Effects#
1// ❌ Bad: Hidden mutation
2let name = 'John';
3function greet() {
4 name = name.toUpperCase();
5 return `Hello, ${name}!`;
6}
7
8// ✅ Good: Pure function
9function greet(name: string): string {
10 return `Hello, ${name.toUpperCase()}!`;
11}Self-Documenting Code#
1// ❌ Redundant comment
2// Check if user is adult
3if (user.age >= 18) {}
4
5// ✅ Self-explanatory
6const ADULT_AGE = 18;
7const isAdult = user.age >= ADULT_AGE;
8if (isAdult) {}Focus on readability, simplicity, and consistency. Code is read more than written.