Student-friendly HTML, CSS, and JavaScript reference with examples
if (age >= 18) { } else { }
When your program has to choose between doing one thing or another, you need an if.
Think of it as a switch on a railway track: the train of thought arrives, the switch is
checked, and the train goes left or right. It can’t go both ways, and it can’t stop.
let age = 16;
if (age >= 18) {
allowAccess();
} else {
denyAccess();
}
age >= 18 is false here, so the train goes right: denyAccess() runs and
allowAccess() never does. Change age to 20 and it goes the other way.
if (condition) {
// this runs when the condition is true
} else {
// this runs when it isn't
}
Exactly one side runs. Never both, never neither.
The else half is optional — leave it off and a false condition simply means nothing
happens.
if (age = 18) { // wrong — this assigns 18 to age, then checks if 18 is truthy
if (age === 18) { // right — this compares age to 18
= assigns a value. === compares two values. if (age = 18) doesn’t ask a question at
all — it sets age to 18 and moves on, and since 18 is truthy, that branch always
runs. Always use === inside an if.