Unit 7 ยท JavaScript

7.4Control Structures

On this page
  1. If, then, else
  2. Switch / case
  3. Loops

If, then, else

JavaScript
let marks = 72;

if (marks >= 75) {
  console.log('Distinction');
} else if (marks >= 50) {
  console.log('Pass');
} else {
  console.log('Fail');
}

Switch / case

Use when comparing one value against many exact options.

JavaScript
let day = 3;
let name;
switch (day) {
  case 1: name = 'Monday'; break;
  case 2: name = 'Tuesday'; break;
  case 3: name = 'Wednesday'; break;
  default: name = 'Unknown';
}

Forgetting break causes fall-through: the next case also runs.

Loops

JavaScript
// for: when you know how many times
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

// while: repeat while a condition is true
let n = 5;
while (n > 0) {
  console.log(n);
  n--;
}

// do...while: runs at least once
let x = 0;
do { x++; } while (x < 3);

// for...of: values of an array (or string)
for (const fruit of ['mango', 'apple']) {
  console.log(fruit);
}

// for...in: keys of an object
for (const key in {a: 1, b: 2}) {
  console.log(key);
}

// break exits the loop; continue skips to the next iteration
for (let i = 1; i <= 10; i++) {
  if (i === 3) continue;
  if (i === 6) break;
  console.log(i);          // 1 2 4 5
}

Try it: Print a multiplication table for a number entered by the user. Then write FizzBuzz: for 1 to 30 print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both, else the number.