By the end of this lesson, learners will:
Writing clean code isn’t just about making it look pretty — it’s about writing code that:
Think of clean code as good communication with your future self and teammates.
✅ Good:
let totalPrice = 49.99;
let userAge = 25;
❌ Bad:
let tp = 49.99;
let a = 25;
Why it matters: Code is read more than it’s written. Good names explain the purpose of the variable.
Most teams use 2 or 4 spaces for indentation. Choose one and stick to it.
✅ Good:
if (score > 90) {
console.log("Excellent!");
}
❌ Bad:
if(score>90){
console.log("Excellent!");
}
Why it matters: Proper indentation makes the structure of your code visible at a glance.
✅ Good:
let x = 5;
let y = 10;
❌ Bad:
let x = 5; let y = 10;
Why it matters: Keeping things on separate lines improves readability and debugging.
let
and const
(Not var
)✅ Use let
for values that will change.
✅ Use const
for values that won’t change.
❌ Avoid var
— it behaves inconsistently due to function scope and hoisting.
Why it matters: let
and const
are safer and more predictable in modern JavaScript.
✅ Good:
// Calculate discounted price for VIP customers
let finalPrice = basePrice * 0.8;
❌ Bad:
// Multiply basePrice by 0.8
let finalPrice = basePrice * 0.8;
Why it matters: Your code already shows what it does — comments should explain why you’re doing it.
Split long pieces of logic into smaller, reusable functions.
✅ Good:
function calculateDiscount(price, rate) {
return price * (1 - rate);
}
❌ Bad:
// long block of logic without any structure
Why it matters: Smaller blocks are easier to understand, test, and reuse.
Use named variables instead of hard-coded values.
✅ Good:
const TAX_RATE = 0.07;
let total = price * TAX_RATE;
❌ Bad:
let total = price * 0.07;
Why it matters: It makes your code easier to understand and maintain.
console.log()
Strategically✅ Use for:
❌ Don’t leave in production code:
console.log("Testing..."); // Remove when no longer needed
Practice | Why It’s Important |
---|---|
Use clear variable names | Improves readability |
Indent consistently | Shows code structure |
Write one statement per line | Easier to read and debug |
Prefer let /const over var | Modern, safer syntax |
Use comments to explain why | Helps future developers (and you!) |
Keep functions short | Easier to test and understand |
Avoid magic numbers | Makes code self-explanatory |
Rewrite this messy code to make it clean:
var x=10;var y=5;if(x>y){console.log("x is greater")}else{console.log("y is greater")}
✅ Clean version:
let x = 10;
let y = 5;
if (x > y) {
console.log("x is greater");
} else {
console.log("y is greater");
}