Beginner
+30 XP

👋 Start learning JavaScript right now — for free!

💻

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:

javascript
💬

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.

javascript
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 (...) and else — always put { at the start and } at the end.

javascript
💬

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.

ExpressionResultWhy
5 === 5truesame numbers
5 === "5"falsenumber ≠ string
"rain" === "rain"truesame strings
"rain" === "Rain"falsedifferent case!

Simple rule: when checking 'is X equal to a specific value' — write ===.

javascript
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:

ExpressionResultExplanation
10 % 2010 divides by 2 evenly
7 % 217 = 3×2 + 1 (remainder 1)
9 % 309 divides by 3 evenly
8 % 328 = 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.

javascript
💬

Run it! Try changing number to 8, 10, 13 — see the result.

javascript
💬

else if — checks the next condition if the previous was false. Try changing score and see which branch fires.

Comparison operators — full table

OperatorMeaningExampleResult
===equal (strict)5 === 5true
!==not equal5 !== 3true
>greater than10 > 5true
<less than3 < 8true
>=greater or equal5 >= 5true
<=less or equal4 <= 10true

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 {}.

Comments

Log In or Start to leave a comment.