Skip to content
Programming contents

Lesson 1.9: Conditions and loops in JavaScript

Deciding and repeating, like in 1.4 and 1.5. In JavaScript what's inside goes between curly braces.

The idea

The same ideas as in 1.4 and 1.5. Two things change:

  • The condition goes in brackets.
  • What's inside goes between curly braces, instead of ending with EndIf or EndWhile.

if and else

JavaScript
const age = Number(prompt("How old are you?"));

if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("You can't vote yet");
}

For more than two paths, else if:

JavaScript
if (n > 0) {
  console.log("Positive");
} else if (n < 0) {
  console.log("Negative");
} else {
  console.log("Zero");
}

Comparing and combining

PseudocodeJavaScript
====
≠!==
≤ and ≥<= and >=
And&&
Or||
Not!

Careful: = stores and === compares. Mixing them up is the most common mistake. You'll also see ==; always use ===, which doesn't convert values behind your back.

while

JavaScript
let counter = 1;

while (counter <= 5) {
  console.log(counter);
  counter = counter + 1;
}

If you forget the line that adds one, the loop never ends and the tab freezes. If that happens, close it and open another.

for

JavaScript
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Inside the brackets there are three parts separated by ;:

  1. Where it starts: let i = 1.
  2. How long it keeps going: i <= 5.
  3. How it moves on: i++, which is the same as i = i + 1.

Try it

Exercise

In the console, write the 3 times table, from 3 × 1 to 3 × 10.

Show the solution
JavaScript
for (let i = 1; i <= 10; i++) {
  console.log("3 x " + i + " = " + 3 * i);
}
Console
3 x 1 = 3
3 x 2 = 6
…
3 x 10 = 30

Summary

  • if, else if and else decide; while and for repeat.
  • The condition goes in brackets and the block between curly braces.
  • === compares; = stores.