Decisions and loops
Branch with if and the ternary, and repeat with for, while and for...of.
18 min
Branching
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}The first true branch runs and the rest are skipped, so put the narrowest test first. Combine tests with && (and), || (or) and ! (not).
Truthy and falsy. In a condition, these count as false: false, 0, "", null, undefined, NaN. Everything else is true, including "0" and [].
Ternary: a one-line choice: const label = age >= 18 ? "adult" : "minor";
Nullish coalescing: value ?? fallback uses fallback only when value is null or undefined (so 0 ?? 5 is 0, but 0 || 5 is 5).
for (let i = 0; i < 3; i++) { // start; keep going while; step
console.log(i); // 0, 1, 2
}
let n = 3;
while (n > 0) { // repeat while the condition is true
n--;
}
for (const letter of "cat") { // each item of a string or array
console.log(letter);
}Use for...of when you just want each item; the classic for when you need the index. break exits a loop and continue skips to the next round.
let total = 0;
for (const n of [4, 8, 15]) {
total += n;
}
console.log(total); // 27Common bug: i <= arr.length runs one step too far, because the last valid index is arr.length - 1.
Loop choice
do something for each item
- Use
for (const x of items)
count from a to b
- Use
for (let i = a; i <= b; i++)
repeat until something happens
- Use
while (condition)
stop early
- Use
break
skip one round
- Use
continue
Write fizzBuzz(n) that returns an array of strings for the numbers 1 to n: "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both, otherwise the number as a string.
fizzBuzz(5) is ["1", "2", "Fizz", "4", "Buzz"].
Your code must satisfy
- fizzBuzz(5)→["1","2","Fizz","4","Buzz"]first five
- fizzBuzz(15)[14]→"FizzBuzz"fifteen
- fizzBuzz(0)→[]zero
- fizzBuzz(6)[5]→"Fizz"six
function fizzBuzz(n) {
}sumTo(n) should add the whole numbers from 1 to n: sumTo(4) is 10. Find the off-by-one bug.
What it does now
sumTo(4) returns 6, not 10: the last number is missing.
Your code must satisfy
- sumTo(4)→10four
- sumTo(1)→1one
- sumTo(100)→5050hundred
- sumTo(0)→0zero
function sumTo(n) {
let total = 0;
for (let i = 1; i < n; i++) {
total += i;
}
return total;
}Print the 7 times table up to 5 × 7, one line each, in the form 1 x 7 = 7.
1 x 7 = 7
2 x 7 = 14
...
5 x 7 = 35Your code must satisfy
- times table
for (let i = 1; i <= 5; i++) {
}“`if (arr.length)` and `if (arr)` mean the same thing.”
Both look like "does the array have something?"
What is actually true
An empty array [] is truthy, so if (arr) is true even when it is empty. To test emptiness, check arr.length === 0 (0 is falsy).
How to catch yourself
Be explicit: compare lengths and use `=== undefined` or `=== null` for missing values.
if / else if / elseruns the first true branch; narrowest test first.0,"",null,undefined,NaNandfalseare falsy; empty arrays and objects are truthy.for...ofvisits each item; the classicforgives you the index;whilerepeats on a condition.- Watch
<versus<=: off-by-one bugs live there.
Control-flow checks.
What does 0 || 5 give?
- A0
- B5
- Ctrue
- Dundefined
What does 0 ?? 5 give?
- A0
- B5
- Cnull
- DNaN
How many times does for (let i = 0; i < 5; i++) run its body?
Which value is truthy?
- A`""`
- B`0`
- C`[]`
- D`null`
What is 5 > 3 ? "yes" : "no"?
- A"yes"
- B"no"
- Ctrue
- Derror
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of JavaScript for Beginners is planned around your week. Free.