Skip to content
Lesson 4 of 10 · JavaScript for Beginners

Decisions and loops

Branch with if and the ternary, and repeat with for, while and for...of.

18 min

Branching

javascript7 lines
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).

javascript12 lines
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.

javascript5 lines
let total = 0;
for (const n of [4, 8, 15]) {
  total += n;
}
console.log(total);   // 27

Common bug: i <= arr.length runs one step too far, because the last valid index is arr.length - 1.

Reference

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
Exercise4 checks
javascript

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
starter code3 lines
function fizzBuzz(n) {
  
}
Exercise4 checks
javascript

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
starter code7 lines
function sumTo(n) {
  let total = 0;
  for (let i = 1; i < n; i++) {
    total += i;
  }
  return total;
}
Exercise1 case
javascript

Print the 7 times table up to 5 × 7, one line each, in the form 1 x 7 = 7.

code4 lines
1 x 7 = 7
2 x 7 = 14
...
5 x 7 = 35

Your code must satisfy

  • times table
starter code3 lines
for (let i = 1; i <= 5; i++) {
  
}
Common misconception

“`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 / else runs the first true branch; narrowest test first.
  • 0, "", null, undefined, NaN and false are falsy; empty arrays and objects are truthy.
  • for...of visits each item; the classic for gives you the index; while repeats on a condition.
  • Watch < versus <=: off-by-one bugs live there.
Check yourself

Control-flow checks.

1Multiple choice

What does 0 || 5 give?

  • A0
  • B5
  • Ctrue
  • Dundefined
2Multiple choice

What does 0 ?? 5 give?

  • A0
  • B5
  • Cnull
  • DNaN
3Numeric answer

How many times does for (let i = 0; i < 5; i++) run its body?

4Multiple choice

Which value is truthy?

  • A`""`
  • B`0`
  • C`[]`
  • D`null`
5Multiple choice

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.