Learning Goals
3 minBy the end of this lesson you will be able to:
- Run code only when a condition is true, using
if. - Offer alternatives with
else ifandelse. - List the six falsy values JavaScript treats as false.
- Print a different message for three different inputs, in one script.
Warm-Up · The Answer Nobody Reads
5 minLast lesson you printed booleans. Useful for you — useless for a visitor.
const heightCm = 132;
const tallEnough = heightCm >= 140;
console.log('Tall enough: ' + tallEnough);Predict together
- What does this print?
- If you were 132 cm and read that on a screen, would you know what to do next?
Reveal
Tall enough: falseTechnically correct, humanly useless. A real ride would say “Sorry, you need to be 140 cm — come back soon!” Getting a different message for each answer is exactly what if is for.
New Concept · Forks in the Road
12 minPicture a junction on the way to school. If it is raining you take the covered walkway; otherwise you cut across the field. Same journey, two routes, chosen by one question.
The shape of an if
const heightCm = 132;
if (heightCm >= 140) {
console.log('Welcome aboard!');
} else {
console.log('Sorry, you need to be 140 cm.');
}Sorry, you need to be 140 cm.Three parts to notice:
- The question goes in round brackets.
- The code to run goes in curly braces.
elseis optional — use it when there is a sensible alternative.
More than two roads
else if adds extra branches. JavaScript checks them in order and stops at the first one that is true.
const score = 72;
if (score >= 80) {
console.log('Grade A');
} else if (score >= 65) {
console.log('Grade B');
} else if (score >= 50) {
console.log('Grade C');
} else {
console.log('Keep practising!');
}Grade BOrder is everything. Put score >= 50 first and every passing score would print Grade C, because it matches first and the rest are never checked. Go from the strictest condition down.
Truthy and falsy
An if does not need a real boolean. JavaScript will judge any value as true-ish or false-ish. Exactly six values are falsy:
false
0
'' // an empty string
null
undefined
NaNEverything else is truthy — including '0', 'false' and empty arrays. This is how you check that a visitor actually typed something:
const typedName = '';
if (typedName) {
console.log(`Hello, ${typedName}!`);
} else {
console.log('Please enter your name.');
}Please enter your name.Handy
if (name) reads nicely for “did they type anything?”
Saves comparing against '' every time.
Careful
0 is falsy — so if (stock) treats zero stock as “nothing there”.
When zero is a real value, compare properly: if (stock > 0).
Why it matters
Every interface you have used branches like this: show the basket if it has items, show a login button if nobody is signed in. In Section D you will do the same in React, and it will still be an if underneath.
Worked Example · The Warung Door
12 minBuild a small opening-hours checker in door.js.
Step 1 — A single check
// door.js — is Warung Aisyah open?
const hour = 15; // 24-hour clock
if (hour >= 8 && hour < 22) {
console.log('We are open — come in!');
}We are open — come in!Change hour to 23 and run it again. Nothing prints at all — with no else, the code simply does nothing.
Step 2 — Say something either way
if (hour >= 8 && hour < 22) {
console.log('We are open — come in!');
} else {
console.log('Sorry, we are closed. Open 8am to 10pm.');
}Sorry, we are closed. Open 8am to 10pm.Step 3 — A friendlier greeting by time of day
let greeting;
if (hour < 12) {
greeting = 'Selamat pagi';
} else if (hour < 19) {
greeting = 'Selamat petang';
} else {
greeting = 'Selamat malam';
}
console.log(`${greeting}! The time is ${hour}:00.`);Selamat petang! The time is 15:00.Notice greeting is declared with let and no value, then filled in by whichever branch runs. That is a common and tidy pattern.
Step 4 — Handle the missing order
A customer arrives but has not chosen yet. Their order is an empty string — falsy — so one if covers it:
const order = '';
if (order) {
console.log(`One ${order}, coming up!`);
} else {
console.log('Take your time — here is the menu.');
}Take your time — here is the menu.Step 5 — A trap worth seeing
Now try the same shape with a quantity of zero:
const rotiCount = 0;
if (rotiCount) {
console.log(`${rotiCount} roti canai ordered.`);
} else {
console.log('No roti canai ordered.');
}No roti canai ordered.What changed? Nothing visible — and that is the danger. Here it happens to read correctly. But if the shop wanted to print “0 roti canai — sold out”, this code never would, because 0 is falsy. When zero is a meaningful value, always compare explicitly with rotiCount > 0.
Try It Yourself
13 minWork in door.js or a new decide.js.
Task 1 — Your own opening hours
Change the opening times to a shop you know, and add a third branch for “closing soon” in the last hour before it shuts.
Test it with at least three different values of
hour.Task 2 — Grades for a Form 3 test
Write a grader with these bands: 80+ is A, 65–79 is B, 50–64 is C, 40–49 is D, below 40 is E. Print the grade for a
markvariable.Check the boundaries carefully — what does your code do with exactly 65? And exactly 40?
Task 3 — Delivery charge
A food app charges RM 5 delivery, free over RM 30, and refuses orders under RM 10. Given an
orderTotal, print one of three messages, including the total the customer will pay.Think about the order of your branches before you write them.
🔥 Mini-Challenge · Everyone Gets an A
8 minNurul's grader gives every student the same grade. Find two mistakes.
// nurul-grader.js — buggy
const mark = 42;
if (mark >= 40) {
console.log('Grade D');
} else if (mark >= 65) {
console.log('Grade B');
} else if (mark >= 80) {
console.log('Grade A');
}
const bonus = 0;
if (bonus) {
console.log('Bonus mark applied: ' + bonus);
}It works if: a mark of 42 gives D, 70 gives B, 85 gives A, 20 gives a “keep practising” message, and a bonus of 0 is still reported.
Reveal the answer
Mistake 1 — the branches are in the wrong order.
mark >= 40 is checked first, and every passing mark satisfies it. A mark of 85 is also 40 or more, so it stops at the first branch and prints Grade D. The later branches can never run.
Fix: order the checks from strictest to loosest. Also add a final else, or marks under 40 print nothing at all.
Mistake 2 — a falsy zero.
if (bonus) is false when bonus is 0, so a zero bonus is silently skipped. If zero is a real value worth reporting, compare it properly.
// nurul-grader.js — fixed
const mark = 42;
if (mark >= 80) {
console.log('Grade A');
} else if (mark >= 65) {
console.log('Grade B');
} else if (mark >= 40) {
console.log('Grade D');
} else {
console.log('Keep practising!');
}
const bonus = 0;
if (bonus >= 0) {
console.log(`Bonus mark applied: ${bonus}`);
}Grade D
Bonus mark applied: 0Both bugs are silent — no error, just wrong answers. Testing with boundary values (39, 40, 64, 65, 79, 80) is how you catch this kind of thing.
Recap
3 minif (condition) { … }runs code only when the condition is true.else ifadds branches;elsecatches everything left.- Branches are checked in order — first match wins, so go strictest first.
- The six falsy values:
false,0,'',null,undefined,NaN. - Everything else is truthy — including
'0'and empty arrays. - When
0is a real value, compare explicitly rather than relying on truthiness. - Test the boundaries of every range.
New words
- Condition — the question inside the round brackets.
- Branch — one possible path through your code.
- Truthy / falsy — how JavaScript judges a non-boolean in an
if. - Boundary value — a number at the very edge of a range, where bugs hide.
📦 Homework
4 min to brief · ~20 min to doRequired
- Write
fare.jsfor a KL bus. Under 7 travels free, 7–17 pays RM 1, adults pay RM 2.50, and over 60 pays RM 1. Print the fare and a friendly sentence for anagevariable. - Test every band and both boundaries (6, 7, 17, 18, 60, 61). Note any surprises in a comment. Bring the file next lesson.
Optional stretch
- Rewrite one simple
if/elseusing the ternary operator:const fare = age < 7 ? 0 : 1;. When is that easier to read, and when is it worse? - Look up
switch. Write one sentence on when it might beat a longelse ifchain.