BeginnerTypeScript · Lesson 4 of 7

Decisions & Loops

if/else, switch, comparison operators, for, for...of and while loops.

Programs make decisions with if / else if / else. Always use strict equality === and !==, which compare without converting types.

switch is tidy when one value is compared against many fixed options. The ternary operator condition ? a : b picks between two values in one expression.

Loops repeat work. Use for...of to walk through the items of an array, a classic for loop when you need the index, and while when you repeat until a condition changes.

grades.tsTypeScript
function gradeFor(score: number): string {
  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: string): string {
  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++) {
  const status = scores[i] >= 30 ? "pass" : "fail";
  console.log("Student " + (i + 1) + ": " + status);
}

let countdown = 3;
while (countdown > 0) {
  console.log("Starting in " + countdown + "...");
  countdown--;
}

Key points

  • Use === / !==, never == / !=.
  • for...of for items, indexed for when you need positions, while for open-ended repetition.
  • Return early from functions to keep if chains flat and readable.

Exercise

Write a FizzBuzz program for 1–50: print "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both, otherwise the number. Then count how many scores in an array are passes (≥ 30) using a loop.

Show solution

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

Check the combined case (divisible by both 3 and 5, i.e. by 15) first — otherwise "Fizz" would win for 15. For counting passes, keep a counter and increase it inside the loop.

fizzbuzz.tsTypeScript
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 scores = [82, 25, 49, 30, 12, 67];
let passes = 0;
for (const score of scores) {
  if (score >= 30) passes++;
}
console.log("Passes: " + passes + " of " + scores.length);   // Passes: 4 of 6

Check your understanding

  1. Why should you use === instead of ==?

  2. Which loop is the natural choice for visiting every item of an array?

  3. In FizzBuzz, why test n % 15 === 0 first?

  4. What does scores[i] >= 30 ? "pass" : "fail" evaluate to when the score is 25?

Ask AI