Skills / JavaScript for the web / Making decisions and repeating
Making decisions and repeating
Programs become useful when they make decisions and repeat work.
if and else. An if runs code only when a condition is true:
if (stock === 0) { message = "Sold out"; } else { message = "In stock"; }
Conditions compare values. Use === for "is equal to" and !== for "is not equal to" (the triple form also checks the type, so "5" === 5 is false, which avoids surprises). Other comparisons are <, >, <= and >=. Combine conditions with && (and) and || (or): if (age >= 18 && hasTicket).
Use else if for more than two outcomes: check the most specific case first.
Loops. A for loop repeats a block a set number of times:
for (let i = 1; i <= 3; i++) { console.log("Round " + i); }
That reads as: start i at 1; keep going while i is 3 or less; add 1 to i after each round. It prints Round 1, Round 2, Round 3.
To go through every item in a list, for...of is clearer:
const prices = [4, 12, 7]; let total = 0; for (const p of prices) { total = total + p; }
After the loop, total is 23.
A while loop repeats as long as a condition stays true. Make sure something inside it eventually makes the condition false, or the loop never ends and the page freezes.
The tutor gives hints, not finished answers. Log in to use it.