if/else Condition
Teach the computer to make decisions based on conditions
if/else = fork in the road
Imagine you're standing at a crossroads. If it's raining — take an umbrella and go left. Otherwise — go right. A program works the same way: it hits a 'fork', checks a condition, and goes one of two ways.
if/else syntax — step by step breakdown
Look at the structure step by step:
Run it and change the value of weather to something else — you'll see the else branch trigger.
What are curly braces { } for?
{ and } are a code block. Inside a block you can write as many lines as needed — they all execute together as one unit.
if (age >= 18) {
console.log("Welcome!"); // line 1
console.log("You have access to"); // line 2
console.log("everything! 🎉"); // line 3
}If the condition is true — all three lines execute. If not — none of them.
Rule: after
if (...),else if (...)andelse— always put{at the start and}at the end.
Change 'rain' to 'sunny' and run — you'll see the else branch.
When to write === (three equals)?
=== means 'exactly equal' — compares both value and data type.
| Expression | Result | Why |
|---|---|---|
5 === 5 | true | same numbers |
5 === "5" | false | number ≠ string |
"rain" === "rain" | true | same strings |
"rain" === "Rain" | false | different case! |
Simple rule: when checking 'is X equal to a specific value' — write ===.
if (name === "Ivan") // is the name exactly 'Ivan'?
if (score === 100) // is the score exactly 100?
if (day === "Monday") // is the day exactly 'Monday'?The % operator — remainder from division
This operator returns the remainder after division. For example:
| Expression | Result | Explanation |
|---|---|---|
10 % 2 | 0 | 10 divides by 2 evenly |
7 % 2 | 1 | 7 = 3×2 + 1 (remainder 1) |
9 % 3 | 0 | 9 divides by 3 evenly |
8 % 3 | 2 | 8 = 2×3 + 2 (remainder 2) |
Checking even numbers — that's why % 2 === 0:
- Even numbers (2, 4, 6, 8...) divide by 2 evenly → remainder = 0
- Odd numbers (1, 3, 5, 7...) when divided by 2 give remainder 1
So number % 2 === 0 literally reads: 'the remainder from dividing the number by 2 equals zero' — meaning the number is even.
Run it! Try changing number to 8, 10, 13 — see the result.
else if — checks the next condition if the previous was false. Try changing score and see which branch fires.
Comparison operators — full table
| Operator | Meaning | Example | Result |
|---|---|---|---|
=== | equal (strict) | 5 === 5 | true |
!== | not equal | 5 !== 3 | true |
> | greater than | 10 > 5 | true |
< | less than | 3 < 8 | true |
>= | greater or equal | 5 >= 5 | true |
<= | less or equal | 4 <= 10 | true |
When to use which:
- Comparing with a specific value →
===or!== - Comparing numbers (bigger/smaller) →
>,<,>=,<=
To remember the syntax: if (CONDITION) { ACTION }. Condition — always in round parentheses (). Action — always in curly braces {}.