Explain it simply
Explain it simply
A computer runs your code once, but people read it many times, including you six months from now. Best practices are not about being strict for its own sake; they are signposts placed exactly where many developers have fallen into the same trap before.
Using const instead of var, for example, promises the reader "this binding is never reassigned". Using === instead of == removes the surprising results caused by JavaScript's automatic type conversion. Each practice protects you from one specific kind of bug.
Problem → Why → Solution
The problem: code that is right once and wrong the second time
The code below totals the paid invoices. The first call returns the correct 150, the second returns 300. The names calc, t, d, s and a say nothing about what the function does, and the == comparison is one more place where a bug can hide.
var t = 0; // global: every call keeps adding to it
function calc(d) {
for (var i = 0; i < d.length; i++) {
if (d[i].s == "paid") t = t + d[i].a;
}
return t;
}
console.log(calc(invoices)); // 150
console.log(calc(invoices)); // 300 <- same input, different answerWhy does this happen?
t is a global variable living outside the function, so every call adds onto the previous total. When a function's result depends on outside mutable state as well as its arguments, the same input no longer guarantees the same output. Declaring the running sum inside the function, comparing with === and choosing clear names removes both the bug and the confusion.
Core concept: each practice blocks a class of bugs
Instead of memorising a list of rules, ask of each one: which bug does this prevent? Once you know the reason, you can decide for yourself in situations no rule covers.
| Practice | Bug it prevents |
|---|---|
| const / let instead of var | Variables leaking out of blocks and accidental reassignment |
| === instead of == | Coercion making 0 == "" and "0" == false true |
| Strict mode | A forgotten declaration silently creating a global |
| No global mutable state | Results that change with call order |
| Validate at the boundary | Bad data crashing deep inside the program |
Make const your default and use let only for bindings you really reassign, such as a counter. const does not freeze an object's properties; it only stops the variable from pointing at a different value. var is function-scoped, so a var declared inside an if or for block is still visible outside it.
When the two operands of == have different types, it converts them before comparing, which is why 0 == "", "0" == false and null == undefined are all true. === returns false straight away when the types differ. Writing 'use strict' at the top of a file turns an assignment to an undeclared variable into a ReferenceError instead of a new global. ES modules (files using import/export) and class bodies are strict automatically.
Clear names and small functions go together. A function that does one job can get a precise name such as subtotal() or assertValidItem(), and it is easy to test. Write comments to explain why a decision was made, not to repeat what the code already says.
- Input arrives at the boundary
- Validate its type and values
- Small pure functions compute
- Return a result, touch no globals
Because data is validated once on entry, the inner functions can trust it instead of repeating the same checks everywhere.
General pattern
'use strict';
const NAMED_CONSTANT = 0.05; // no magic numbers
function doOneThing(input, { option = DEFAULT } = {}) {
if (!isValid(input)) throw new TypeError("why it was rejected");
const result = helper(input); // const unless reassigned
return result; // return, do not mutate globals
}
if (actual === expected) { /* strict equality */ }The function checks its input first and throws an error that says why when it is wrong. Accepting options as a destructured object with defaults keeps call sites readable. It returns its result instead of changing outside state.
Example: a clean order total
This example gathers the lesson's practices in one place: a named constant, functions that each do one job, an options object with a default, validation at the entry point, and errors caught and reported clearly. Compare it with the legacy calc() above: the same kind of task, but every name now tells you its job.
'use strict';
const TAX_RATE = 0.05; // a named constant instead of a "magic number"
function assertValidItem(item) {
if (typeof item.price !== "number" || item.price < 0) {
throw new TypeError(`Invalid price for ${item.name}: ${item.price}`);
}
}
function subtotal(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
function orderTotal(items, { taxRate = TAX_RATE } = {}) {
if (!Array.isArray(items)) {
throw new TypeError("items must be an array");
}
items.forEach(assertValidItem);
const net = subtotal(items);
return Math.round(net * (1 + taxRate) * 100) / 100;
}
const cart = [
{ name: "Tea", price: 2.5, qty: 2 },
{ name: "Cake", price: 4, qty: 1 },
];
console.log(`Subtotal: ${subtotal(cart)}`);
console.log(`Total: ${orderTotal(cart)}`);
console.log(`Total without tax: ${orderTotal(cart, { taxRate: 0 })}`);
for (const badInput of [null, [{ name: "Gift", price: "free", qty: 1 }]]) {
try {
orderTotal(badInput);
} catch (error) {
console.log(`Rejected: ${error.message}`);
}
}Code breakdown
- Named constant
const TAX_RATE = 0.05; // a named constant instead of a "magic number"Naming 0.05 once, instead of scattering it through the code, makes its meaning obvious and means a rate change is a one-line edit.
- One job per function
function subtotal(items) {subtotal() only adds and assertValidItem() only checks. Each name tells you the job, and each function can be tested on its own.
- Options object with a default
function orderTotal(items, { taxRate = TAX_RATE } = {}) {A call like orderTotal(cart, { taxRate: 0 }) explains what the 0 means. The = {} prevents a destructuring error when no options are passed at all.
- Validate at the boundary
items.forEach(assertValidItem);Every item is checked before any maths happens, so a price of "free" becomes a TypeError that names the problem instead of a NaN total further down.
- Handle errors deliberately
console.log(`Rejected: ${error.message}`);Catching an error and reporting it is different from swallowing it: the output says exactly why each bad input was rejected.
Subtotal: 9
Total: 9.45
Total without tax: 9
Rejected: items must be an array
Rejected: Invalid price for Gift: freeFour pitfalls worth knowing early
Some traps get their own lessons later in this tutorial. Knowing their names now means you will recognise them when they turn up in a code review.
| Pitfall | How to avoid it |
|---|---|
| Losing this inside a callback | Pass an arrow function or use bind() when handing a method over as a callback |
| Deeply nested callbacks (callback hell) | Use promises and async/await so the steps read top to bottom |
| Unhandled async errors | Wrap await in try/catch or attach .catch() |
| Memory leaks | Remove event listeners, timers and big caches you no longer need |
In real projects
Where this shows up in real projects
On team projects nobody relies on memory for these practices; tools enforce them. ESLint rules such as no-var, eqeqeq (which flags == and !=) and no-unused-vars highlight the traps right in the editor, and a formatter such as Prettier ends every debate about indentation and quotes. The CI pipeline refuses to merge a change whose lint or tests fail.
A common refactor splits a long Express route handler into small parse, validate, compute, save and respond functions. After the split, the compute step can be unit-tested without a database, and validation errors all come out of one place in one consistent shape. Before making code clever for performance, measure with a profiler first; the readable version is usually fast enough.
Common mistakes
Common mistakes
1. Thinking const makes an object immutable
After const settings = { theme: "dark" }, settings.theme = "light" still works; only settings = {} is blocked with a TypeError. Use Object.freeze() when you really need the object itself to stay unchanged (it freezes one level deep).
2. Catching errors and doing nothing
An empty catch such as try { save(); } catch (e) {} hides the bug: the save failed, nobody was told, and the app carries on. Log it, show it to the user, or rethrow it with added context.
3. Comments that repeat the code
A comment like i++; // add 1 to i tells the reader nothing new and turns into a lie once the code changes. Only comments that explain why are worth keeping, for example "prices are stored in cents to avoid floating-point rounding errors".
Best practices
Best practices
- Add ESLint and a formatter on day one and set your editor to run them on save.
- When a function grows longer than one screen, or its name needs an "and", it is time to split it.
- Return a new value instead of mutating an array or object you received as an argument, so the caller's data never changes behind their back.
Mini challenge
Mini challenge: refactor the legacy invoice code
Rewrite calc() from the problem section using this lesson's practices. Calling it repeatedly must give the same result every time.
- Name the function totalPaid(invoices) and use no global variables
- Keep "paid" in a named constant and compare with ===
- Reject non-array input with a TypeError
- Call it twice to show the result is stable, and print the error message
// Legacy version (do not keep it):
// var t = 0;
// function calc(d) {
// for (var i = 0; i < d.length; i++) {
// if (d[i].s == "paid") t = t + d[i].a;
// }
// return t;
// }
// TODO: sample data with id, status ("paid" or "draft") and amount fields
function totalPaid(invoices) {
// TODO: throw a TypeError when invoices is not an array
// TODO: keep paid invoices (compare with ===) and add up their amounts
}
// TODO: print the total twice, then print the error for totalPaid("oops")Expected: With paid amounts 120 and 30: First call: 150 Second call: 150 Rejected: TypeError: invoices must be an array
Show hint
Pick the paid invoices with filter(), then add them with reduce((sum, invoice) => sum + invoice.amount, 0). The running total lives inside reduce, so no global is needed.
Show solution
const STATUS_PAID = "paid";
const invoices = [
{ id: "A1", status: "paid", amount: 120 },
{ id: "A2", status: "draft", amount: 80 },
{ id: "A3", status: "paid", amount: 30 },
];
function totalPaid(list) {
if (!Array.isArray(list)) {
throw new TypeError("invoices must be an array");
}
return list
.filter((invoice) => invoice.status === STATUS_PAID)
.reduce((sum, invoice) => sum + invoice.amount, 0);
}
console.log(`First call: ${totalPaid(invoices)}`);
console.log(`Second call: ${totalPaid(invoices)}`);
try {
totalPaid("oops");
} catch (error) {
console.log(`Rejected: ${error.name}: ${error.message}`);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Each best practice blocks one kind of bug; remember the rule together with its reason.
- Default to const, use let only when you reassign, and avoid var and global mutable state.
- Use === everywhere; the coercion in == produces surprises like 0 == "" being true.
- Validate input at the boundary, keep functions small and well named, comment the why, and let ESLint and a formatter check the rest.
MDN — JavaScript Guide — MDN Web Docs