Conditional Statements (if, else if, else)
Every program eventually needs to do different things depending on a value. JavaScript uses if, else if, and else for this — with curly braces marking each block, unlike Python's indentation.
let age = 20;
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}You are an adult
=== vs. ==
JavaScript has two equality operators, and the difference genuinely matters: === checks value and type together (strict equality), while == converts types before comparing (loose equality), which can produce surprising results.
console.log(5 === 5); console.log(5 === "5"); console.log(5 == "5");
true false true
Always use === unless you have a specific reason not to. == quietly converts "5" and 5 to be equal, which is rarely what you actually intended, and is a common source of subtle bugs.
Chaining conditions with else if
let score = 75;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("F");
}C
JavaScript checks each condition top to bottom and stops at the first one that's true — score >= 70 matches before it ever reaches else, so "C" is printed and everything after is skipped.
Next: for loops — repeating code over every item in a collection.
Practice exercise
Set age = 16. Print "Minor" if age is less than 18, otherwise print "Adult".