Make decisions with if/else and repeat work with for and while loops.
Why this matters
So far your code has run top to bottom, once. Real programs make decisions (is this password long enough? is the player out of lives?) and repeat work (add up every item in a cart, check every field in a form). Conditionals and loops are how you do both. They are called control flow, because they control which lines run and how many times.
if, else if, else
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
grade(95); // "A"
grade(85); // "B"
grade(42); // "F"
JavaScript checks each condition in order and runs the first block whose condition is true, then skips the rest. That is why order matters: if you checked score >= 70 first, a 95 would get a "C".
Comparison and logic operators
| operator | meaning | example |
|---|---|---|
=== / !== | equal / not equal (strict) | role === "admin" |
< <= > >= | less / greater than | age >= 18 |
&& | and: both must be true | age >= 13 && age <= 19 |
|| | or: at least one is true | day === "Sat" || day === "Sun" |
! | not | !isLoggedIn |
Truthy and falsy
An if does not need a real boolean. JavaScript treats these values as falsy: false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy, including "0", [] and {}.
const name = "";
if (!name) {
console.log("Please enter your name");
}
This is handy, but be careful: if (count) is false when count is 0, which may be a perfectly valid value.
for loops
A for loop repeats a block a counted number of times. It has three parts: start, condition, step.
function sumTo(n) {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i; // same as total = total + i
}
return total;
}
sumTo(4); // 1 + 2 + 3 + 4 = 10
To visit each item in an array, for...of is clearer, because you do not need to manage an index:
const prices = [4, 10, 6];
let total = 0;
for (const price of prices) {
total += price;
}
// total is 20
while loops
A while loop repeats as long as its condition is true. Use it when you do not know in advance how many times you will loop.
function countdown(n) {
const steps = [];
while (n > 0) {
steps.push(n);
n--; // move towards the end, or the loop never stops
}
return steps;
}
countdown(3); // [3, 2, 1]
The danger with while is an infinite loop: if nothing inside ever makes the condition false, the program hangs. Always check that something changes on every pass.
break and continue
breakleaves the loop immediately.continueskips to the next pass.
for (const n of [3, 8, -1, 5]) {
if (n < 0) break; // stop at the first negative number
if (n % 2 === 0) continue; // skip even numbers
console.log(n); // prints 3
}
A worked example: combining both
Count how many scores in a list are passing (70 or more):
function countPassing(scores) {
let passing = 0;
for (const s of scores) {
if (s >= 70) {
passing++;
}
}
return passing;
}
countPassing([95, 60, 70, 88, 42]); // 3
A loop with an if inside, plus a counter or total outside, is one of the most common shapes in all of programming. You will meet it again as filter and reduce in module 3.
Common mistakes
- Wrong order of conditions. Check the most specific or highest range first.
- Using
=in a condition.if (x = 5)assigns 5 and is always true. Use===. - Off-by-one loops.
i < nruns n times from 0;i <= nruns n + 1 times. Decide which you need. - Infinite
whileloops. Make sure the loop variable changes. - Forgetting that
0and""are falsy. Compare explicitly when those are valid values.
Quick recap
if / else if / elseruns the first true branch, in order.- Combine conditions with
&&,||and!; know your falsy values. forfor counted loops,for...offor arrays,whilefor "until something happens".- A loop plus an
ifplus a counter solves a huge number of problems.
Try it
Open the Do tab: write grade, sumTo and countdown.