Lesson 5 of 6 · 12 min · 1 hands-on step
Clean Code & Refactoring
Turn messy code into readable code without changing what it does, protected by tests.
Code is read far more than it's written
You'll write a line once and read it (or a teammate will) dozens of times. Clean code optimizes for the reader.
Five habits with the biggest payoff
1. Names that explain themselves
// ❌
const d = 86400000;
function calc(a, b) { return a * b * 0.2; }
// ✅
const MS_PER_DAY = 86_400_000;
function taxFor(price, quantity) { return price * quantity * TAX_RATE; }
2. Small functions that do one thing. If you need "and" to describe it, split it.
3. No magic numbers. Give constants names: PASS_MARK, MAX_RETRIES.
4. Return early instead of nesting deep
function canCheckout(user, cart) {
if (!user) return "Please log in";
if (cart.length === 0) return "Your cart is empty";
if (!user.address) return "Add a shipping address";
return "OK";
}
console.log(canCheckout({ address: "1 Main St" }, ["book"]));5. Delete dead code. Git remembers it if you ever need it back.
Refactoring safely
Refactoring = changing the structure without changing the behavior. The safety net is tests: run them before, make a small change, run them again. Green means you didn't break anything.
That's exactly what the practice below does. The tests lock in the behavior, and you're free to clean up.
AI assistants are great at refactoring suggestions. With tests in place, you can accept or reject them confidently.
🧪 Practice
f works, but nobody can read it. Refactor it into a function called summarizeScores(scores) with clear names and small steps. The tests check that it returns exactly the same result as before.
It returns { count, average, passed }: the number of scores, the average (rounded to 1 decimal), and how many are 60 or above.
function f(a) {
let x = 0, y = 0;
for (let i = 0; i < a.length; i++) { x += a[i]; if (a[i] >= 60) y++; }
return { count: a.length, average: a.length ? Math.round((x / a.length) * 10) / 10 : 0, passed: y };
}
// Rename and clean up. Keep the behavior identical.
function summarizeScores(scores) {
return f(scores);
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What does refactoring mean?
What should you have before refactoring?
Create a free account to track your progress.