Conditionals & Loops
Making decisions with if/else and switch, and repeating code with loops.
Comparison & Logical Operators
| Comparison | Meaning |
|---|---|
== | Equal value (loose) |
=== | Equal value AND type (strict) |
!= / !== | Not equal / not equal value or type |
< > <= >= | Less / greater than (or equal) |
| Logical | Meaning |
|---|---|
&& | 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
| Loop | Use |
|---|---|
for | Known number of iterations. |
while | Repeats while the condition is true. |
do...while | Always runs at least once. |
for...in | Iterates over object properties. |
for...of | Iterates 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 iterationsfor (var i = 0; i < 5; ) {console.log(i);}// Iterate over iterable valuesfor (var fruit fruits) {console.log(fruit);}