AI Hints
Home›JavaScript Tutorial›Debugging and Clean Code
JavaScript · Lesson 113 of 138

Clean Code

Code people can read.

⏱ 2 min read▶ Video at 2:16:16🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Code is read far more often than it's written. By your teammates, and by you, six months later. Clean code is code that's easy to read, easy to change, and hard to break.

Clean Code
From the video: Clean Code
  • Read more than written
  • Teammates, and future you
  • Easy to read and change

Before and after

On the left, short names, magic numbers, and one function doing everything. On the right, clear names, a named constant for the tax rate, and small functions that each do one job. Both work the same, but only one is easy to understand.

Hard to read

  • function f(a) { ... }
  • x * 1.2
  • One huge function

Clean

  • function totalWithTax(items)
  • price * (1 + TAX_RATE)
  • Small, focused functions

A cleaner version

Here's the clean version. A constant names the tax rate. Subtotal does one job, and with tax does another. Early returns handle bad input first, so the main logic isn't nested. And the names explain the code, so it barely needs comments. Run it.

app.jsjavascript
const TAX_RATE = 0.2;

function subtotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

function totalWithTax(items) {
  if (!Array.isArray(items) || items.length === 0) return 0;
  return Math.round(subtotal(items) * (1 + TAX_RATE) * 100) / 100;
}

const cart = [{ price: 4.5, qty: 2 }, { price: 10, qty: 1 }];
console.log(totalWithTax(cart), totalWithTax([]));
Output
22.8 0

Summary

Clean code uses clear names, small functions, named constants, and early returns. Next, the most common JavaScript mistakes, and how to avoid them.

Key takeaways
  • Clear names
  • Small functions
  • No magic numbers
Next up: Common Mistakes — and how to avoid them