Making decisions with if, else and comparisons
Make JavaScript choose what to do: compare values with === and >, branch with if, else if and else, combine tests with && and ||, and understand truthy and falsy values.
🎯 By the end of this lesson you will be able to:
- Compare values with ===, !==, <, >, <= and >=
- Write if, else if and else chains
- Combine conditions with &&, || and !, and predict truthy and falsy values
Outline
What you'll learn and why it matters
Programs constantly make decisions. Is the password long enough? Is the basket over the free-delivery limit? Is the shop open right now? Conditions let your code take different paths depending on the answer.
Comparing values
A comparison gives a boolean: true or false.
const age = 17;
console.log(age >= 18);
console.log(age < 18);
console.log(age === 17);
console.log(age !== 17);Console (Chrome and Edge)
false true true false
| Operator | Means |
|---|---|
=== | Is equal to (same value and same type) |
!== | Is not equal to |
< > | Less than, greater than |
<= >= | Less than or equal, greater than or equal |
console.log("5" === 5);
console.log(Number("5") === 5);Console (Chrome and Edge)
false true
if, else if and else
if runs a block of code only when its condition is true. The block goes inside curly braces { }.
const basketTotal = 650;
if (basketTotal >= 500) {
console.log("Free delivery!");
} else {
console.log(`Add ${500 - basketTotal} more for free delivery.`);
}Console (Chrome and Edge)
Free delivery!
With more than two choices, chain else if. JavaScript checks each condition from the top and runs only the first block whose condition is true:
const marks = 72;
let grade;
if (marks >= 85) {
grade = "A";
} else if (marks >= 70) {
grade = "B";
} else if (marks >= 40) {
grade = "C";
} else {
grade = "Try again";
}
console.log(`Marks ${marks}: grade ${grade}`);Console (Chrome and Edge)
Marks 72: grade B
72 is not at least 85, so the first test fails. It is at least 70, so grade becomes "B" and the rest of the chain is skipped, even though 72 is also at least 40. Order matters: put the strictest test first.
Combining conditions: &&, || and !
| Operator | Read as | True when |
|---|---|---|
a && b | a and b | Both are true |
a || b | a or b | At least one is true |
!a | not a | a is false |
const hour = 21;
const isHoliday = false;
const isOpen = hour >= 8 && hour < 20 && !isHoliday;
console.log(`Open now: ${isOpen}`);
const isWeekend = true;
const canSleepIn = isWeekend || isHoliday;
console.log(`Sleep in: ${canSleepIn}`);Console (Chrome and Edge)
Open now: false Sleep in: true
Truthy and falsy
if does not need a real boolean. JavaScript treats some values as falsy (counted as false). Everything else is truthy.
| Falsy values (the complete list you need) | Typical meaning |
|---|---|
false | No |
0 | Zero |
"" (empty string) | Nothing typed |
null and undefined | No value |
NaN | A failed number conversion |
const typedName = "";
if (typedName) {
console.log(`Hello, ${typedName}!`);
} else {
console.log("Please type your name.");
}Console (Chrome and Edge)
Please type your name.
A short if: the conditional operator
For choosing between two values, condition ? valueIfTrue : valueIfFalse fits on one line:
const stock = 0;
const label = stock > 0 ? "In stock" : "Sold out";
console.log(label);Console (Chrome and Edge)
Sold out
Practice
Guided exercise
Ticket prices
A museum charges 0 for children under 5, 50 for ages 5 to 17, 100 for adults, and 60 for people 60 and over. Work out the price for age = 64 and print it.
- Create
const age = 64;andlet price;. - Test the youngest group first:
if (age < 5). - Then
else if (age < 18), thenelse if (age >= 60), thenelsefor other adults. - Print the price with a template literal.
Show the solution
const age = 64;
let price;
if (age < 5) {
price = 0;
} else if (age < 18) {
price = 50;
} else if (age >= 60) {
price = 60;
} else {
price = 100;
}
console.log(`Age ${age}: ₹${price}`);Console (Chrome and Edge)
Age 64: ₹60
How to get there: Each test only runs if all the ones above it failed, so age < 18 already knows the person is at least 5. Change age to 3, 12, 30 and 64 to test every branch.
Your turn
Password check
Given const password = "chai2026";, print Strong if it is at least 8 characters long and includes a digit 2, otherwise print Weak. Use length and includes.
Show the solution
const password = "chai2026";
if (password.length >= 8 && password.includes("2")) {
console.log("Strong");
} else {
console.log("Weak");
}Console (Chrome and Edge)
Strong
How to get there: Both parts must be true for && to be true. Real password rules check much more, but the pattern of combining tests with && is the same.
Common mistakes
Using = instead of === in a condition
You see: The condition is always true and the variable gets overwritten
Fix: Compare with ===; = only stores values.
Comparing typed text with a number using ===
You see: "18" === 18 is false, so the check never passes
Fix: Convert first: Number(typedAge) === 18.
Putting the widest test first in an else-if chain
You see: Everyone gets the first grade
Fix: Order tests from most specific (strictest) to least.
Writing if (age > 5 && < 18)
You see: SyntaxError: Unexpected token '<'
Fix: Repeat the variable: age > 5 && age < 18.
Recap
- Comparisons give true or false; use
===and!==, never the loose==. - if / else if / else runs only the first block whose condition is true.
&&needs both,||needs either,!flips true and false.- Falsy values: false, 0, "", null, undefined and NaN.
a ? b : cpicks between two values.
Key terms
- Condition
- An expression that is true or false, used to decide which code runs.
- Boolean
- A value that is either true or false.
- Falsy
- A value that counts as false in a condition, such as 0 or an empty string.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. What does `"7" === 7` give?
2. With `const marks = 90`, which block runs? if (marks >= 40) { A } else if (marks >= 85) { B }
3. When is `a || b` false?
4. Which value is truthy?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.