Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 5

Conditionals & Loops

Making decisions with if/else and switch, and repeating code with loops.


Comparison & Logical Operators

ComparisonMeaning
==Equal value (loose)
===Equal value AND type (strict)
!= / !==Not equal / not equal value or type
< > <= >=Less / greater than (or equal)
LogicalMeaning
&&AND — both conditions must be true
||OR — at least one must be true
!NOT — reverses the boolean value
if (age >= 18 && country === "MY") {
  // eligible
}

Use strict equality === — it compares value AND type, which is best practice.

Conditional Statements: if and if...else

if (hour < 18) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

switch (new Date().getDay()) {   // selects today's day
  case 6:
    text = "Saturday";
    break;
  case 0:
    text = "Sunday";
    break;
  default:
    text = "Weekday";
}

JavaScript Loop Types

LoopUse
forKnown number of iterations.
whileRepeats while the condition is true.
do...whileAlways runs at least once.
for...inIterates over object properties.
for...ofIterates over iterable values.
// for — known number of iterations
for (var i = 0; i < 5; i++) {
  console.log(i);
}

// while — repeats while condition is true
var i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

// do...while — always runs at least once
var j = 0;
do {
  console.log(j);
  j++;
} while (j < 5);

// for...in — iterates over object properties
for (var key in person) {
  console.log(key);
}

// for...of — iterates over iterable values
for (var fruit of fruits) {
  console.log(fruit);
}

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the conditional and the loops.

if (hour < 18) {
greeting = "Good day";
} {
greeting = "Good evening";
}
 
// Known number of iterations
for (var i = 0; i < 5; ) {
console.log(i);
}
 
// Iterate over iterable values
for (var fruit fruits) {
console.log(fruit);
}