Conditions and loops

A program that only runs its statements from top to bottom cannot make a decision. Two forms make one: if with a condition around a block, and a loop around a block that runs more than once. Both take a condition, and every value in JavaScript may stand in one: the false values are false, 0, "", null, undefined and NaN.

This lesson adds the parts that make the forms usable: else if chains, the conditional operator for a value chosen in one expression, switch for a list of exact cases, the three loop forms, and the two ways out of a loop. Every program is run, and the output on the page is what the runtime printed.

if, else and the conditional operator

if takes a condition in parentheses and a block in braces. The first branch whose condition is true runs, and the rest are skipped. An else if chain reads top to bottom, so the order of the tests decides the answer when more than one of them would be true.

The conditional operator does the same job for one value. It is written as condition ? whenTrue : whenFalse and is an expression, so it can stand on the right side of a declaration. The program grades three scores with a chain and labels each one with the operator.

const scores = [92, 67, 45]; for (const score of scores) { let grade; if (score >= 90) { grade = 'A'; } else if (score >= 60) { grade = 'B'; } else { grade = 'C'; } const label = score >= 90 ? 'excellent' : 'keep going'; console.log(`${score}: ${grade} (${label})`); }

node conditions.js

92: A (excellent)
67: B (keep going)
45: C (keep going)

The score of 67 answers the second test, because the first one failed, and 45 falls through to the last branch. Each iteration of the loop declares its own grade with let, so no value carries over from the pass before it.

switch and fallthrough

switch compares one value with each case using strict equality and runs the code from the first match. Without a break or a return, the run continues into the next case; that is called fallthrough, and it is a feature when two cases share one body. The program uses it for 1 and 2 and returns from every branch.

function describe(value) { switch (value) { case 0: return 'zero'; case 1: case 2: return 'small'; default: return 'large'; } } console.log(describe(0), describe(2), describe(9));

node switch.js

zero small large

The call with 2 prints small because its case has an empty body and falls into the body of 1. A default branch runs when no case matches, and it does not have to be last; placing it last is a convention that costs nothing.

for, while and do-while

A for loop puts its initialisation, condition and step in one line, and an i that counts from 1 to 5 is the smallest useful example. A while loop repeats while its condition is true and is the right form when the number of passes is unknown; a do-while runs its body once before the first test. for...of walks the values of an array without an index, which is what most loops over data should use.

The program below counts every number from 1 to 5 except 3, searches a small matrix for the value 5 and stops, and prints a countdown with process.stdout.write so that its numbers share one line.

let total = 0; for (let i = 1; i <= 5; i += 1) { if (i === 3) { continue; } total += i; } console.log('total without 3:', total); const matrix = [ [1, 2, 3], [4, 5, 6], ]; let found = null; outer: for (const row of matrix) { for (const value of row) { if (value === 5) { found = value; break outer; } } } console.log('found:', found); let countdown = 3; while (countdown > 0) { process.stdout.write(String(countdown) + ' '); countdown -= 1; } console.log('liftoff');

node loops.js

total without 3: 12
found: 5
3 2 1 liftoff

The sum is 12 rather than 15 because the pass with 3 skipped the addition, and the nested loops stop at the first row that holds the value. The countdown writes each number with a trailing space and the single console.log at the end supplies the newline.

break, continue and labels

continue ends the current pass and goes to the next one; break ends the loop. Inside two nested loops, a bare break leaves only the inner one, so the outer loop keeps running. A label in front of the outer loop gives the break a name: break outer leaves both loops at once.

A label is a name and a colon before a statement, and it exists only for break and continue. Modern code reaches for a function with an early return more often than for a label, and the lesson on functions shows that form; the label stays for the case where the loops are the clearest way to write the walk.

Exercises

  1. Add a score of 90 to the array in conditions.js. Which grade does it receive, and why does the conditional operator call it excellent?
  2. Remove the empty case 1: label from switch.js. What does describe(1) return now?
  3. Change the countdown in loops.js into a do-while loop. What does it print when the starting number is 0?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which values are false in a condition?

    Answer

    false, 0, "", null, undefined and NaN

    Those six are falsy; an empty array and an empty object are objects and therefore true.

  2. What does the conditional operator look like?

    Answer

    condition ? whenTrue : whenFalse

    It is an expression that chooses one of two values, guarded by a question mark and a colon.

  3. Which comparison does switch use for its cases?

    Answer

    Strict equality

    A case matches only when the value and the type are the same, which is why switch on a number does not match a string.

  4. What happens without a break or a return in a case?

    Answer

    The run continues into the next case

    Fallthrough is the rule, and two cases that share a body use it on purpose.

  5. What does this program print? let total = 0; for (let i = 1; i <= 5; i += 1) { if (i === 3) { continue; } total += i; } console.log(total);

    Answer

    12

    The pass with 3 skips the addition, so the sum is 1 + 2 + 4 + 5.

  6. What does a bare break inside two nested loops leave?

    Answer

    Only the inner loop

    A bare break leaves the nearest loop, and a label on the outer loop is what reaches further.

  7. What does this program print? for (const value of [10, 20, 30]) { process.stdout.write(value + " "); }

    Answer

    10 20 30

    for...of walks the values, and write adds no newline, so the three numbers share one line.

  8. When does the body of a do-while loop run?

    Answer

    Once before the condition is tested

    The body runs first and the test comes after it, so a do-while always runs at least once.

  9. What is a label used for in JavaScript?

    Answer

    As a name for break and continue

    A label names a statement so that break or continue can reach it from inside a nested loop.

  10. Which loop form walks the values of an array without an index?

    Answer

    for...of

    for...of gives the values themselves, while for...in gives the property names as strings.

The code on this page was run with Node.js 24.22.1 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image