Beginner · Strings, decisions and loops · topic 7 of 61 · 20 min
Decisions with if and else
Explanation
Why programs need decisions
Real programs react to data: give a discount if the cart is big, show an error if the password is short, charge late fees if a bill is overdue. A conditional statement runs some code only when a condition holds.
const marks = 72;
if (marks >= 90) {
console.log('Grade A');
} else if (marks >= 60) {
console.log('Grade B');
} else if (marks >= 35) {
console.log('Grade C');
} else {
console.log('Fail');
}Order matters
Because only the first true branch runs, put the most specific or highest condition first. If you test marks >= 35 before marks >= 90, a student with 95 gets grade C, because 95 >= 35 is already true.
Truthy and falsy
The condition inside if (...) can be any value. JavaScript converts it to true or false. Exactly eight values are falsy: false, 0, -0, 0n, '' (empty string), null, undefined and NaN. Every other value is truthy, including '0', 'false', [] and {}.
if ('0') console.log('"0" is truthy'); // runs
if ([]) console.log('[] is truthy'); // runs
if ('') console.log('never printed'); // empty string is falsy
const name = '';
if (!name) console.log('Please enter a name'); // runsCombining conditions
const age = 22;
const hasLicence = true;
if (age >= 18 && hasLicence) console.log('Can drive');
const day = 'Sun';
if (day === 'Sat' || day === 'Sun') console.log('Weekend');Write each comparison in full. if (day === 'Sat' || 'Sun') is a bug: 'Sun' on its own is a truthy string, so the condition is always true.
Guard clauses: return early
Deeply nested ifs are hard to read. A guard clause checks a bad case at the top of a function and returns straight away. The main logic then sits at the left edge, not five levels deep.
function withdraw(balance, amount) {
if (amount <= 0) return 'Invalid amount';
if (amount > balance) return 'Insufficient balance';
return `New balance: ${balance - amount}`;
}
console.log(withdraw(1000, 300)); // New balance: 700Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Decisions with if and else · 1/6
In this lesson your programs will start making decisions with if and else.
Prefer a video by a teacher? Find free videos on “javascript if else truthy falsy tutorial” on YouTube ↗
In real life: An electricity bill with slabs
State electricity boards charge by slabs: the first units are cheap and higher usage costs more per unit. A billing program decides the rate with if / else if. The numbers below are made-up example rates, not any board's real tariff.
function ratePerUnit(units) {
if (units <= 100) return 3;
if (units <= 300) return 5;
return 7;
}
console.log(ratePerUnit(80), ratePerUnit(250), ratePerUnit(420));Practice (0/3 done)
Write a function grade(marks): 90 or more is "A", 60–89 is "B", 35–59 is "C", below 35 is "F".
Write a function ticketPrice(age): children under 5 travel free (0), children 5–11 pay 250, adults pay 500, and seniors aged 60 or more pay 300. If age is negative or not a number, return null.
This isWeekend(day) always returns true. Fix the condition so it is true only for "Sat" and "Sun".
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- switch, the ternary operator and lookup tablesStrings, decisions and loops · same module
- Loops: for, while, do…while, for…of and for…inStrings, decisions and loops · same module
- Operators and conditionsFrontend Web Development · JavaScript basics
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Decisions: if, else and the ternaryJava Programming (Core to Spring Boot) · Control flow and methods
- Booleans and comparisonsPython Programming · Text and decisions
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which of these values is truthy?
Answer: '0'
'0' is a non-empty string, so it is truthy.
How many branches of an if / else if / else chain can run at most?
Answer: One
Only the first branch whose condition is true runs.
const stock = 0; if (stock) { A } else { B }. Which runs?
Answer: B
0 is falsy, so the else branch runs, even though 0 is a real stock value.
What is a guard clause?
Answer: An early return for a bad case at the start of a function
Guard clauses handle invalid cases first and return, keeping the main code flat.
Which value is falsy?Related
Answer: 0
The number 0 is falsy. The strings "0" and "false" and an empty array are truthy.
string? name = null; Is if (name != null && name.Length > 2) safe?Related
Answer: Yes, because && stops after the first false part
&& short-circuits: when name is null, name.Length is never evaluated.
How many branches of if / else if / else can run?Related
Which of these values is falsy?Related
Answer: 0
The number 0 is falsy. The other three are non-empty strings, so they are truthy.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Strings, decisions and loops” before its exam: switch, the ternary operator and lookup tables, Loops: for, while, do…while, for…of and for…in, Loop patterns that solve real problems.
- Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and closures. 61 topics left in the course before the final exam.