Clean Code: Pro Best Practices

Clean Code: Pro Best Practices in JavaScript: Junior developers write code that "works." Senior developers write code that humans can read.

Concept Explanation

Junior developers write code that "works." Senior developers write code that humans can read. You'll spend far more time reading old code than writing new code — so clarity, not cleverness, is the skill that pays. Clean code is cheaper to change, safer to fix, and faster for a team to trust.


The Golden Rules

  1. Avoid globals: keep variables inside functions with const/let. Global variables are "public trash cans" — anyone can drop garbage in.
  2. Small functions: if a function passes ~20 lines, it's usually doing too much. Split it until each piece does one job.
  3. Naming is half the job:
  • const d = 30; ❌
  • const daysUntilExpiry = 30; ✅

Syntax or Core Structure

Guard clauses beat nested ifs

// Hard to read: the "happy path" is buried
function pay(user) {
  if (user) {
    if (user.active) {
      if (user.balance > 0) { /* ...the real work... */ }
    }
  }
}

// Clean: bail out early, keep the main logic flat
function pay(user) {
  if (!user) return;
  if (!user.active) return;
  if (user.balance <= 0) return;
  // ...the real work, un-indented...
}

Common Mistakes

  1. Loose equality: == triggers weird coercions (0 == "" is true!). Use === and !== always.
  2. Magic numbers: if (status === 3) — what is 3? Name it: const STATUS_SHIPPED = 3;.
  3. Silent failures: an empty catch (e) {} hides bugs forever. At the very least, log the error.

Best Practices

  • One job per function: name it with a verb, and if the name needs an "and", split it.
  • Prefer const: reach for let only when reassignment is real; never var.
  • Comment the "why", not the "what": good names explain what code does; comments should explain the reason behind a tricky choice.
  • Format automatically: let a tool like Prettier handle spacing and quotes so reviews focus on logic, not style.

Practice Exercises

  1. The Renamer: Take a piece of code with variables like x, y, arr and rename them to be perfectly descriptive.
  2. The Refactor: Find a long function you've written and split it into two smaller, independent functions.
  3. The Guard Clause: Rewrite a deeply nested if block using early return guard clauses.