Making Decisions: Conditionals and Loops
So far, our programs have run from top to bottom, one line after another. Real programs need to make decisions ("if the cart is empty, show a message") and repeat work ("for each item in the list, add tax"). This chapter covers the two tools for that: conditionals (choosing which code runs) and loops (running code many times).
Conditionals: Choosing with `if`
An if statement runs a block of code only when a condition is true. A condition is an expression that evaluates to true or false, usually built with comparison operators like === (equal to) or > (greater than).
const temperature = 28;
if (temperature > 25) {
console.log("It's warm — wear a t-shirt.");
}Add else to handle the other case, and else if to test more options:
const temperature = 12;
if (temperature > 25) {
console.log("Warm");
} else if (temperature > 10) {
console.log("Mild");
} else {
console.log("Cold");
}Only the first condition that matches runs; the rest are skipped.
A common trap: `=` vs `===`
=assigns a value:x = 5===compares values:x === 5
Writing if (x = 5) assigns instead of comparing, which is almost always a bug.
Loops: Repeating Work
A for loop repeats a block a set number of times. It has three parts: a starting counter, a condition to keep going, and a step.
for (let i = 1; i <= 5; i++) {
console.log(`Count is ${i}`);
}Here, i starts at 1, and the loop body runs as long as i <= 5. After each run, i++ adds 1. The output is 1, 2, 3, 4, 5.
A while loop repeats as long as its condition stays true. Use it when you don't know in advance how many times you need to repeat:
let cups = 0;
while (cups < 3) {
cups++;
console.log(`Drank cup number ${cups}`);
}Combining Both
Conditionals inside loops let you filter or act on some items:
const scores = [45, 78, 92, 60];
for (let i = 0; i < scores.length; i++) {
if (scores[i] >= 60) {
console.log(`Score ${scores[i]}: pass`);
} else {
console.log(`Score ${scores[i]}: fail`);
}
}scores.length is the number of items in the array, so the loop automatically adapts to any list size.
Show diagram source
flowchart TD
A[Start loop: i = 0] --> B{i < scores.length?}
B -- no --> E[Done]
B -- yes --> C{scores[i] >= 60?}
C -- yes --> F[Log pass]
C -- no --> G[Log fail]
F --> H[i++]
G --> H
H --> BExercise
What does this print? let n = 2; while (n < 10) { n = n * 2; } console.log(n);
Show answer
16. The loop doubles n (2 → 4 → 8 → 16) and stops when n is no longer less than 10, so the final value is 16.
Exercise
Rewrite the scores loop using a for loop that counts only the failing scores into a variable, then log how many failed.
Show answer
let fails = 0; for (let i = 0; i < scores.length; i++) { if (scores[i] < 60) { fails++; } } console.log(fails);
Spotted a mistake, or code that does not work?