Control flow
Conditionals, loops, and the truthiness rules that drive them.
- Branch with if/else and iterate with for-of
- Use === over == and understand truthiness
- Iterate arrays with for-of and forEach
The three universal shapes of logic — sequence, selection, iteration (the
fundamentals lesson) — in JavaScript syntax. Blocks are delimited by { }, and
conditions live in ( ).
Selection: if / else
if (score > 90) {
grade = "A";
} else if (score > 80) {
grade = "B";
} else {
grade = "C";
}Use === not ==
JavaScript has two equality operators, and this trips up everyone:
===compares value and type, with no surprises:1 === "1"isfalse.==coerces types first, producing oddities like1 == "1"beingtrueand0 == ""beingtrue.
Always use === (and !==). The coercing == causes subtle bugs.
Truthiness
In a condition, every value is "truthy" or "falsy." The falsy values are worth
memorising: false, 0, "", null, undefined, and NaN. Everything else
is truthy — a quirk tied to JavaScript's dynamic (not static) typing. This is why if (items.length) reads as "if there are any items."
Loops over arrays
For iterating a collection, for...of is the clean, modern choice:
const names = ["Ada", "Alan"];
for (const name of names) {
console.log(name);
}Arrays also have forEach (and map/filter you'll meet next), which take a
function per element:
names.forEach((name) => console.log(name));Where to go next
Next: strings and template literals — working with text the modern way.