Lesson 3 of 18 · 0 of 2 exercises solved

Control Flow & Loops

You will learn how to make decisions with if and switch and how to repeat work with and . This is how a program reacts to different data.

// if / else if / else
const score = 75;

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("Try harder");
}

// Ternary operator — one-line if/else
const result = score >= 60 ? "Pass" : "Fail";
console.log(result);   // Pass

// Nullish coalescing — use right side if left is null/undefined
const username = null ?? "Guest";
console.log(username);   // Guest

// Optional chaining — safely access nested properties
const user = { profile: { name: "Alice" } };
console.log(user?.profile?.name);    // Alice
console.log(user?.address?.city);    // undefined (no error)
JavaScript sandboxCtrl+Enter runs
// Classic for loop
for (let i = 0; i < 5; i++) {
  console.log(i);   // 0, 1, 2, 3, 4
}

// for...of — iterate over array values (use this for arrays)
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}

// for...in — iterate over object keys (use this for objects)
const person = { name: "Alice", age: 30, city: "Paris" };
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// while loop
let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}

// Array methods replace many loops in modern JS
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);      // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
JavaScript sandboxCtrl+Enter runs

Practice

Fill the out array with FizzBuzz for 1 to 15: "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both, otherwise the number itself.

Exercise

FizzBuzz, JavaScript edition

2 checks
const out = []
for (let n = 1; n <= 15; n++) {
  out.push(n)
}
console.log(out.join(' '))
 
JavaScript sandboxCtrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Using a while loop, push the numbers 5 down to 1 into countdown, then push the "Liftoff!".

Exercise

Countdown with while

2 checks
const countdown = []
let n = 5

// while n is at least 1 ...

console.log(countdown)
 
JavaScript sandboxCtrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Check yourself

Quick check

Which comparison should you use by default, and why?

Finished reading?2 exercises still open. You can come back to them later.

Tip: use the ← and → keys to move between lessons.