Skills / JavaScript for the web / Making decisions and repeating

JavaScript for the web, lesson 2 of 8

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.

Try it: Write a loop that goes through the list [3, 8, 15, 4] and counts how many numbers are greater than 5. Log the count (it should be 2).

Check yourself

1. Why use === instead of == in JavaScript?

2. How many times does for (let i = 1; i <= 3; i++) run?

3. What is the risk with a while loop?