Topic 03 / 15
Operators & Control Flow
if / else if / else
const score = 87;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else {
console.log("Keep practising");
}Logical operators: && (and), || (or), ! (not). They short-circuit and return the deciding value, not a boolean — the basis of many JS idioms.
The Ternary
const label = score >= 60 ? "pass" : "fail";Perfect for choosing between two values. Nest them and your reviewer will hunt you down.
Modern Defaults: ?? and ?.
Nullish coalescing ?? — fallback only when null/undefined (unlike ||, which also overrides 0 and “”):
const count = userInput ?? 10; // 0 stays 0
const countBad = userInput || 10; // 0 becomes 10 — usually a bugOptional chaining ?. — safe deep access that yields undefined instead of throwing:
const city = user?.address?.city; // undefined if any link missing
const first = users?.[0]; // works with indexes
onSave?.(); // call only if definedswitch
switch (status) {
case "draft":
case "review": // fall-through groups cases
showEditor();
break; // forget break = bugs
case "published":
showArticle();
break;
default:
show404();
}Loops
// classic counter
for (let i = 0; i < 5; i++) {
console.log(i);
}
// for...of — values of any iterable (your default for arrays)
for (const tech of ["js", "css", "react"]) {
console.log(tech);
}
// for...in — KEYS of an object (not for arrays!)
const user = { name: "Ravi", score: 82 };
for (const key in user) {
console.log(key, user[key]);
}
// while
let tries = 0;
while (tries < 3) {
tries++;
}break exits the loop; continue skips to the next iteration. In practice you’ll often replace loops with array methods (map, filter) — coming up in the arrays topic.