Chapter 2 · Decide, repeat, reuse
Decisions and loops
Step 1 of 22 · Concept
Questions with true or false answers
By the end of this lesson your programs decide and repeat. Both start with a condition: a question answered true or false.
| condition | means | with a = 7, b = 10 |
|---|---|---|
a === b | equal | false |
a !== b | not equal | true |
a < b | less than | true |
a > b | more than | false |
a <= b | at most | true |
a >= b | at least | false |
Step 2 of 22 · Concept
if runs a block
const temp = 30;
if (temp > 25) {
console.log("Hot");
} else {
console.log("Not hot");
}
console.log("Done");
ifchecks the condition in its brackets. When it istrue, the block after it runs.- The braces
{and}mark the block. Indentation is for people; Node reads the braces. elsehas its own block, forfalse.
Step 3 of 22 · Try it
Try it: the stray semicolon
Run it: it is 18 degrees, yet it says Hot. A ; ends the if too early, so the block always runs.
Remove that ; and run it again: only Done prints.
The ; is on line 2, right after (temp > 25). Without it, the block belongs to the if.
Step 4 of 22 · Concept
More than two choices: else if
For more than two choices, chain the conditions with else if.
- Node checks the conditions in order, one by one.
- It runs the block of the first condition that is
true, and skips the rest. elseat the end catches everything left.
Step 5 of 22 · Quiz
What will it print?
Type what this program prints.
const score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
Step 6 of 22 · Demo
See it run
This copy has a misspelt name in its else block. Run it and compare with your answer: no error.
Then change score to 40 and run it. The else block runs at last, and Node stops with
ReferenceError: consle is not defined. Fix the name.
Step 7 of 22 · Concept
Two conditions at once
| write | counts as true when |
|---|---|
a && b | both are true |
a || b | at least one is true |
!a | a is false |
Any value can stand where a condition goes. 0, "", null, undefined and NaN count as false; every other value
counts as true.
Step 8 of 22 · Quiz
Predict the trap
answer is "no". Type the missing line.
const x = 7;
console.log(x >= 7 && x < 10, !(x > 10));
console.log(5 == "5", 5 === "5");
const answer = "no";
if (answer === "y" || "yes") {
console.log("Yes");
} else {
console.log("No");
}
Step 9 of 22 · Demo
See the trap
Run it and compare with your answer. Then compare each side in the if, answer === "y" || answer === "yes", and
run it again: now it says No.
Step 10 of 22 · Exercise
Your turn: not a score
A score must be from 0 to 100. This program grades two scores, 105 and -5, with one chain each.
Add a first check to both chains: when score is below 0 or above 100, log score, "is not a score". The
program must print:
105 is not a score
-5 is not a score
The new check goes first, before score >= 90: the first true condition wins, and 105 would get an A otherwise. And -5 is the other side: one condition must catch both.
In each chain, ask whether score is below 0 or above 100, joined with ||. The old first if becomes an else if.
if (score < 0 || score > 100) {
Step 11 of 22 · Concept
A for loop counts for you
for (let i = 1; i <= 5; i++) {
console.log(i);
}
A for loop runs its block again and again, one round at a time. Its header has three parts:
| part | here | when |
|---|---|---|
| start | let i = 1 | once, before the first round |
| condition | i <= 5 | before every round: false ends the loop |
| step | i++ | after every round |
Step 12 of 22 · Quiz
Predict the rounds
Type what this program prints.
for (let i = 0; i < 3; i++) {
if (i % 2 === 0) {
console.log(i, "even");
} else {
console.log(i, "odd");
}
}
Step 13 of 22 · Demo
A loop and a decision
An if inside a for: a block in a block, so every round decides again. Run it and compare with your answer. Then
change i < 3 to i < 6 and run it again.
Step 14 of 22 · Trace
Watch the boxes change
total and i are boxes in the module's frame (lesson 2). The i made in the for header belongs to the loop: it
is gone when the loop ends (lesson 7). Press Next to run one round at a time.
let total = 0;
for (let i = 1; i <= 3; i++) {
total += i;
}
console.log("Total:", total);- The loop starts:
iis 1,totalis 0. Line 3 is next. total += imadetotal1. Then line 2 ran: the step madei2, andi <= 3is true.totalis 3,iis 3. Line 3 is next again.totalis 6. The step madei4:i <= 3is false, so the loop is over, and itsiis gone.- Line 5 logged
Total: 6. The program is finished.
Step 15 of 22 · Exercise
Your turn: 1 to 100
Add up all the numbers from 1 to 100 with a for loop. The program must print:
Sum: 5050
Mind the condition: i <= 100. With i < 100, the loop stops at 99 and 100 is never added.
A for from 1 while i <= 100, stepping with i++. Inside its block, add i to total, as the trace did.
for (let i = 1; i <= 100; i++) {
Step 16 of 22 · Concept
while: repeat until
let n = 10;
while (n < 100) {
console.log(n);
n *= 2;
}
console.log("Past 100:", n);
while repeats its block as long as its condition is true. Use it when you cannot count the rounds in advance.
n | n < 100 |
|---|---|
| 10, 20, 40, 80 | true: log n, double it |
| 160 | false: the loop ends |
Step 17 of 22 · Try it
Try it: a loop that never ends
Run it. It does not stop by itself: n stays 10, so n < 100 stays true.
Press Stop. Then put n *= 2; in place of the comment, and run it again.
n *= 2; doubles n (lesson 3). Inside the block, after console.log(n);, it changes what n < 100 asks.
Step 18 of 22 · Exercise
Your turn: the road to 1
A famous puzzle. Start from a number n and repeat: halve an even n; make an odd n into 3 * n + 1. It always
seems to reach 1, but nobody has proved that it always does.
Start from n 6. While n is more than 1, log n, then apply the rule. After the loop, log the final 1:
6
3
10
5
16
8
4
2
1
n / 2; alone computes a half and throws it away: n stays 6 and the loop never ends (press Stop). Write n = n / 2;.
A while (n > 1). Inside its block: console.log(n);, then an if on whether n is even, with an else.
if (n % 2 === 0) {
Step 19 of 22 · Exercise
Your turn: FizzBuzz
Log the numbers from 1 to 15, each on its own line, but:
FizzBuzzinstead of a number divisible by 3 and by 5,Fizzinstead of a number divisible by 3,Buzzinstead of a number divisible by 5.
The output starts 1, 2, Fizz, 4, Buzz and ends with FizzBuzz.
The first true condition wins. 15 divides by 3, so a check for n % 3 === 0 first would log Fizz: check n % 15 === 0 before it.
Inside the loop, one chain of four: divisible by 15, else by 3, else by 5, else the number itself.
if (n % 15 === 0) {
Step 20 of 22 · Check yourself
Check yourself: multiples of 7
Log the first seven multiples of 7, one per line, then a count:
- Loop
ifrom 1 to 7;nis7 * i, the next multiple. - Log
n, "*"whennis even or over 40; else lognalone. - After the loop, log
Marked:and how many got a*.
The output must be:
7
14 *
21
28 *
35
42 *
49 *
Marked: 4
Make the count and n before the loop, with 0 in each. In the loop, one if with its else, as in the even and odd demo: the if block logs the * and adds 1.
Step 21 of 22 · Challenge · optional
Challenge: countdown
Optional.
Count down from 10 to 1, one number per line, then log Go!. The output must be:
10
9
8
7
6
5
4
3
2
1
Go!
A for can count down: start at 10, keep going while i is more than 0, and take 1 away each round.
i-- takes 1 from i, as i++ adds 1. The header is let i = 10, then i > 0, then i--.
for (let i = 10; i > 0; i--) {
Step 22 of 22 · Recap
Recap
- A condition such as
score >= 70givestrueorfalse. Compare with===, never==. if/else if/else, each with a block in braces: the first true condition wins.&&needs both sides true,||at least one; compare each side.for (let i = 1; i <= 5; i++): start, condition, step.whilerepeats while its condition istrue. Something inside must change it, or press Stop.
Next: lesson 7 names a piece of work and calls it: functions.
Review
3 questions from this lesson, in a new order each time. Answer from memory: 2 of 3 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
const temp = 18;
if (temp > 25); {
console.log("Hot");
}
console.log("Done");
const score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else {
consle.log("Grade: C");
}
const x = 7;
console.log(x >= 7 && x < 10, !(x > 10));
console.log(5 == "5", 5 === "5");
const answer = "no";
if (answer === "y" || "yes") {
console.log("Yes");
} else {
console.log("No");
}
let score = 105;
if (score >= 90) {
console.log(score, "Grade: A");
} else if (score >= 70) {
console.log(score, "Grade: B");
} else {
console.log(score, "Grade: C");
}
score = -5;
if (score >= 90) {
console.log(score, "Grade: A");
} else if (score >= 70) {
console.log(score, "Grade: B");
} else {
console.log(score, "Grade: C");
}
for (let i = 0; i < 3; i++) {
if (i % 2 === 0) {
console.log(i, "even");
} else {
console.log(i, "odd");
}
}
let total = 0;
// add every number from 1 to 100 to total
console.log("Sum:", total);
let n = 10;
while (n < 100) {
console.log(n);
// something is missing here
}
console.log("Past 100:", n);
let n = 6;
// while n is more than 1:
// log n
// halve n if it is even, else make it 3 * n + 1
console.log(n);
for (let n = 1; n <= 15; n++) {
console.log(n);
}
// 1. loop i from 1 to 7: n is 7 * i
// 2. log n, "*" when n is even or over 40
// 3. log Marked: and how many got a *
console.log("Go!");