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
- Avoid globals: keep variables inside functions with
const/let. Global variables are "public trash cans" — anyone can drop garbage in. - Small functions: if a function passes ~20 lines, it's usually doing too much. Split it until each piece does one job.
- 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
- Loose equality:
==triggers weird coercions (0 == ""istrue!). Use===and!==always. - Magic numbers:
if (status === 3)— what is 3? Name it:const STATUS_SHIPPED = 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 forletonly when reassignment is real; nevervar. - 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
- The Renamer: Take a piece of code with variables like
x,y,arrand rename them to be perfectly descriptive. - The Refactor: Find a long function you've written and split it into two smaller, independent functions.
- The Guard Clause: Rewrite a deeply nested
ifblock using earlyreturnguard clauses.