BeginnerJavaScript · Lesson 3 of 7

Decisions & Loops

if / else, switch, the ternary operator, truthy and falsy values, for, for...of and while.

if, else if and else choose what runs. Combine conditions with && (and), || (or) and ! (not). The ternary condition ? a : b picks one of two values.

JavaScript treats some values as "falsy" in conditions: false, 0, "", null, undefined and NaN. Everything else is truthy — so if (name) checks that a name was given.

Use for...of to loop over the items of an array or string, a classic for loop when you need a counter, and while when repeating until something changes.

grades.jsJavaScript
function gradeFor(score) {
  if (score >= 75) return "A";
  else if (score >= 65) return "B";
  else if (score >= 45) return "C";
  else if (score >= 30) return "D";
  return "F";
}

function remarkFor(grade) {
  switch (grade) {
    case "A": return "Excellent";
    case "B": return "Very good";
    case "C": return "Good";
    case "D": return "Satisfactory";
    default: return "Fail";
  }
}

const scores = [82, 67, 49, 31, 18];

for (const score of scores) {
  const grade = gradeFor(score);
  console.log(`${score} -> ${grade} (${remarkFor(grade)})`);
}

for (let i = 0; i < scores.length; i++) {
  console.log(`Student ${i + 1}: ${scores[i] >= 30 ? "pass" : "fail"}`);
}

const typedName = "";
console.log(typedName ? `Hello ${typedName}` : "Please enter your name");

let countdown = 3;
while (countdown > 0) {
  console.log(`Starting in ${countdown}...`);
  countdown--;
}
Runs in your browser · JavaScript

Key points

  • if / else if / else for decisions; switch for one value against many options.
  • Know the falsy values: false, 0, "", null, undefined, NaN.
  • for...of for items, counted for for positions, while for open-ended repetition.

Exercise

Write FizzBuzz for 1–50. Then loop over an array of student names and print only the names longer than five letters, numbered from 1.

Show solution

Try the exercise yourself first — then compare your approach with this one.

FizzBuzz checks 15 first so it isn't caught by the 3 or 5 tests. For the names, keep a separate counter so the numbering is 1, 2, 3 for the names that pass the filter, not their original positions.

loops.jsJavaScript
for (let n = 1; n <= 50; n++) {
  if (n % 15 === 0) console.log("FizzBuzz");
  else if (n % 3 === 0) console.log("Fizz");
  else if (n % 5 === 0) console.log("Buzz");
  else console.log(n);
}

const names = ["Amina", "Baraka", "Juma", "Rehema", "Ali", "Zawadi"];
let count = 0;
for (const name of names) {
  if (name.length > 5) {
    count++;
    console.log(`${count}. ${name}`);
  }
}
// 1. Baraka
// 2. Rehema
// 3. Zawadi
Runs in your browser · JavaScript

Check your understanding

  1. Which of these values is truthy?

  2. Which loop runs at least once, even if its condition is false from the start?

  3. What does break do inside a loop?

  4. In a switch, what happens if a case has no break or return?

Ask AI