Modern JavaScript (ES2015 onward) added features that make code shorter and safer. This closing chapter collects the ones you'll reach for every day, then the professional habits that separate readable, maintainable code from the kind that becomes a liability.
Optional chaining & nullish coalescing
?. safely reads deep properties that might not exist (no more "cannot read property of undefined"), and ?? provides a fallback only for null/undefined — unlike ||, which also triggers on 0 and "":
user?.profile?.email // undefined instead of throwinguser?.save?.() // call a method only if it existsconst count = data.count ?? 0; // 0 stays 0 (?? only catches null/undefined)const count2 = data.count || 0; // ✗ turns a real 0 into 0... but also "" and false
Destructuring & spread
const { name, package: pkg = 0 } = student; // rename + defaultconst [first, ...rest] = tools; // first item + the restconst merged = { ...defaults, ...overrides }; // merge objectsconst combined = [...a, ...b]; // combine arraysfunction log({ level = "info", message }) { // destructure paramsconsole.log(`[${level}] ${message}`);}
Handy shorthands
const name = "Aanya";const obj = { name }; // shorthand for { name: name }const greet = (n) => `Hi ${n}`; // arrow + template literalarr.length ? doWork() : skip(); // ternaryconst value = input ?? computeDefault();
Clean-code habits
- Name things well.
const activeStudentsbeatsconst arr2. Code is read far more than written. - Small functions. One job each; if you can't name it simply, it's doing too much.
- const by default,
letonly when reassigning, nevervar. - Fail fast. Validate inputs and return early rather than nesting deep
ifs. - Prefer immutability and pure functions where practical (Chapter 13).
- Use a linter & formatter (ESLint + Prettier) so style is automatic and consistent.
Practice
Refactor a snippet that uses nested ifs and && guards to use ?. and ??. Destructure a function's options parameter with defaults. Then take a long function and split it into two well-named smaller ones.
Key takeaways
- 01Optional chaining ?. safely reads maybe-missing properties; nullish ?? falls back only on null/undefined.
- 02Destructuring (with defaults/rename) and spread make working with objects and arrays concise.
- 03Use shorthands (property shorthand, arrows, ternary) where they aid readability.
- 04Clean-code habits: good names, small single-purpose functions, const-by-default, early returns, immutability.
- 05Automate style with ESLint + Prettier — clear beats clever.
