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
EndIforEndWhile.
if and else
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:
if (n > 0) {
console.log("Positive");
} else if (n < 0) {
console.log("Negative");
} else {
console.log("Zero");
}
Comparing and combining
| Pseudocode | JavaScript |
|---|---|
= | === |
≠ | !== |
≤ 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
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
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Inside the brackets there are three parts separated by ;:
- Where it starts:
let i = 1. - How long it keeps going:
i <= 5. - How it moves on:
i++, which is the same asi = i + 1.
Try it
In the console, write the 3 times table, from 3 × 1 to 3 × 10.
Show the solution
for (let i = 1; i <= 10; i++) {
console.log("3 x " + i + " = " + 3 * i);
}
3 x 1 = 3
3 x 2 = 6
…
3 x 10 = 30
Summary
if,else ifandelsedecide;whileandforrepeat.- The condition goes in brackets and the block between curly braces.
===compares;=stores.