LEARN TO CODE | JAVASCRIPT | 01 LANGUAGE FOUNDATIONS

01.4 Conditions and loops

Make decisions, repeat instructions safely and trace a running total through a loop one statement at a time.

01 | PROGRAMS NEED CHOICES AND REPETITION

A quiz should congratulate a successful player but offer encouragement after a low score. A game should repeat its round instructions rather than require the programmer to copy the same lines ten times.

Selection chooses which code to run. Iteration repeats code. Both are part of control flow: the order in which instructions execute.

We will start with a single decision, then build loops whose progress you can follow. Keep the examples small enough to predict before running them.

Keep index.html and script.js in the same VS Code folder. Put the current example into script.js, save it, open or refresh index.html in your browser and look in that page’s Developer Tools Console.

Replace the previous example unless a task explicitly says to add to it. Pasting several independent examples together can redeclare the same let or const name. The downloadable examples use a separate folder for each complete program.

02 | ONE CONDITION WITH IF

const score = 8;
if (score >= 5) {
  console.log("Target reached");
}
console.log("Round finished");

The expression in parentheses is the condition. Here it evaluates to true, so JavaScript executes the statements inside the braces. These statements are the body of the if block.

With score = 3, the condition would be false and the body would be skipped. The final log is outside the braces, so it still runs. Indentation helps people see the structure; braces define the block.

A body simply means the statements belonging to a structure. We will use the same word for the statements repeated by a loop.

03 | TWO POSSIBLE ROUTES WITH ELSE

const score = 3;
if (score >= 5) {
  console.log("Target reached");
} else {
  console.log("Keep practising");
}

The else body runs when the if condition is false. In this two-branch structure, exactly one body runs when execution reaches it. You do not write a second condition after else.

Always use braces in these lessons, even for one statement. Avoid a stray semicolon immediately after if (...), because that can end the controlled statement before the block you intended.

TRY IT YOURSELF

Test score values 4, 5 and 6. Which two cases reach the target?

Reveal guidance

5 and 6 satisfy score >= 5. Testing just below, exactly on and just above the boundary helps expose an incorrect > instead of >=.

04 | SEVERAL BANDS WITH ELSE IF

const score = 75;
if (score >= 80) {
  console.log("Gold");
} else if (score >= 50) {
  console.log("Silver");
} else {
  console.log("Bronze");
}

JavaScript tests from top to bottom and uses the first true branch. With 75, the first comparison is false and the second is true, so Silver is logged.

The higher threshold comes first. If score >= 50 came first, a score of 90 would already enter that branch and never reach the gold test. Order matters when conditions overlap.

This chain differs from separate if statements: independent if statements can each run if their conditions are true.

05 | COMBINE BOOLEAN CONDITIONS

const age = 14;
const hasPermission = true;
if (age >= 12 && hasPermission) {
  console.log("Activity approved");
}
const isTeacher = false;
const isClubLeader = true;
console.log(isTeacher || isClubLeader);
console.log(!hasPermission);
Logical operators
Operator Meaning for boolean operands Example result
&& AND: both true true && false is false
|| OR: at least one true true || false is true
! NOT: reverse the boolean !true is false

For a range, write age >= 12 && age <= 18. Do not use the mathematical-looking chain 12 <= age <= 18: JavaScript evaluates it in stages and it does not represent the intended range check.

Conditions convert values to boolean when needed. false, 0, an empty string, null, undefined and NaN are falsy; a non-empty string such as "false" is truthy. Prefer explicit boolean comparisons while learning. Also, && and || can return operand values rather than literal booleans; these examples deliberately use boolean operands.

06 | A FOR LOOP REPEATS A BODY

for (let round = 1; round <= 3; round++) {
  console.log(`Round ${round}`);
}
console.log("Finished");

The body is the code inside the loop’s braces: here, one console.log statement. One execution of the body is an iteration or pass.

The header has three parts separated by semicolons. let round = 1 runs once at the start. round <= 3 is checked before each pass. round++ runs after each completed pass to increase round by 1.

After the body runs with round equal to 3, the update makes round 4. The condition is then false, so execution continues after the loop. The header’s let round is scoped to this loop.

Trace the loop, including the final failed test
Condition check Result Body output Value after update
1 <= 3 true Round 1 2
2 <= 3 true Round 2 3
3 <= 3 true Round 3 4
4 <= 3 false No body execution Loop ends

07 | WATCH A RUNNING TOTAL

let total = 0;
for (let round = 1; round <= 3; round++) {
  total = total + round;
  console.log(`Round ${round}: total ${total}`);
}
console.log(`Final total: ${total}`);

total starts outside the loop so the accumulated value survives between passes. Each pass adds the current round to the old total. The statement means “keep what I have, then add this round’s value”.

If total = 0 were inside the body, each pass would reset the earlier work. If you wrote total = round, you would replace the total instead of accumulating it.

STEP THROUGH THE TOTAL

Ready: total = 0. Select Next step to test the loop condition.

Execution trace
Step What happens Total

08 | WHILE CHECKS BEFORE EACH PASS

let countdown = 3;
while (countdown > 0) {
  console.log(countdown);
  countdown--;
}
console.log("Go!");

while tests its condition before running the body. countdown-- subtracts 1, moving the value towards the stopping condition. When countdown reaches 0, the next test is false and the loop stops.

If countdown begins at 0, the body runs zero times and Go! is still logged. A pre-condition loop does not promise to run once.

for is convenient for a clear counter-based repetition. while is useful when continuation is described by a condition. You can express this countdown with either, but in both versions you must understand how it ends.

09 | AVOID A LOOP THAT NEVER FINISHES

If you forget the update in the countdown, countdown remains 3 and the condition stays true. A tight infinite loop can make the browser tab unresponsive.

Before running a loop, identify its starting value, its continuation condition and the change that eventually makes that condition false. Check whether the change goes in the right direction.

Do not deliberately run an infinite loop as a test. If one happens accidentally, stop or close the practice tab, fix the source in VS Code, save and reopen it. Do not immediately restore the same broken page.

TRY IT YOURSELF

A loop starts at 1 and should log 1, 2, 3, 4. Should its condition be count < 4 or count <= 4?

Reveal guidance

Use count <= 4. The < 4 version stops before the pass for 4. This is an off-by-one error: the boundary allows one too few or too many passes.

10 | BREAK AND CONTINUE HAVE DIFFERENT JOBS

for (let number = 1; number <= 5; number++) {
  if (number === 3) {
    continue;
  }
  console.log(number);
}

continue skips the remaining body statements for the current pass. In this for loop, the update still runs, then the condition is checked again. It skips logging 3 but does not stop the whole loop.

for (let number = 1; number <= 5; number++) {
  if (number === 3) {
    break;
  }
  console.log(number);
}

break exits this loop immediately, so 3, 4 and 5 are not logged. Use either statement when it clarifies a genuine requirement; the simple conditions in earlier examples are often enough.

11 | MINI BUILD: ROUND SCORE REPORT

const playerName = "Alex";
const pointsPerRound = 4;
let total = 0;

for (let round = 1; round <= 3; round++) {
  total += pointsPerRound;
  console.log(`Round ${round}: ${total} points`);
}

if (total >= 10) {
  console.log(`${playerName} reached the target.`);
} else {
  console.log(`${playerName} needs more practice.`);
}

The total is updated during the loop. The final decision runs after repetition is complete, so it checks the finished score rather than each intermediate value.

TRY IT YOURSELF

Change pointsPerRound to 3, predict every line and run it. Then explain where to place total = 0 and why.

Reveal guidance

The round totals become 3, 6 and 9, followed by Alex needs more practice. Initialising total before the loop preserves progress instead of resetting it on every pass.

KEEP LEARNING

Previous page 01 Language foundations: challenges

Download Section 01 example programs

Further reading: JavaScript in VS Code · Grammar and types · Template literals · Loops and iteration