If / Else Statements
Control your program's flow with if/else statements. Learn comparison operators, truthy/falsy values, and how to make decisions in JavaScript.
Control your program's flow with if/else statements. Learn comparison operators, truthy/falsy values, and how to make decisions in JavaScript.
An if statement runs a block of code only when a condition is true.
const age = 20;
if (age >= 18) { console.log("adult");}if (age >= 18) { console.log("adult");} else { console.log("minor");}One branch or the other always runs.
const 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");}JavaScript checks each condition in order and stops at the first true.
| Operator | Meaning |
|---|---|
=== |
Strictly equal |
!== |
Strictly not equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
Always use === over ==. Triple equals checks value AND type, which is almost always what you want.
Any value can be used as a condition. Falsy values (0, '', null, undefined, NaN, false) evaluate to false. Everything else is truthy:
const name = "";
if (name) { console.log("has name"); // skipped — empty string is falsy} else { console.log("no name"); // runs}Combine conditions with && (AND) and || (OR):
if (age >= 18 && hasTicket) { console.log("enter");}
if (isAdmin || isModerator) { console.log("access granted");}