Skip to content

Beginner · Strings, decisions and loops · topic 7 of 61 · 20 min

Decisions with if and else

Explanation

if runs a block of code only when a condition is true; else if and else handle the other cases. Conditions do not have to be true or false: JavaScript treats some values as falsy (like 0, empty text, null and undefined) and everything else as truthy. Early returns keep decision code flat and readable.

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.

javascript
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');
}
Prints Grade B. JavaScript checks from the top and runs only the FIRST branch whose condition is true.

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

javascript
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'); // runs
Careful: Truthiness hides real values. if (stock) treats a stock of 0 as "missing". When 0 or an empty string is a valid value, compare exactly: if (stock === undefined) or if (stock !== null && stock !== undefined), or use ??.

Combining conditions

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

javascript
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: 700
Think of it like this: A guard clause is like the security guard at an office gate. He checks your ID card at the entrance and sends you away immediately if something is wrong. Once you are inside, nobody checks again at every desk.
Tip: Always use braces { } around the body of an if, even for one line in a team project. Code without braces is easy to break when someone adds a second line later.

Need 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

if / else

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.

javascript
function ratePerUnit(units) {
  if (units <= 100) return 3;
  if (units <= 300) return 5;
  return 7;
}
console.log(ratePerUnit(80), ratePerUnit(250), ratePerUnit(420));
Prints 3 5 7.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function grade(marks): 90 or more is "A", 60–89 is "B", 35–59 is "C", below 35 is "F".

Task 2 · Code · Javascript

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.

Task 3 · Code · Javascript

This isWeekend(day) always returns true. Fix the condition so it is true only for "Sat" and "Sun".

Quick quiz

Question 1

1.Which of these values is truthy?

Question 2

2.How many branches of an if / else if / else chain can run at most?

Question 3

3.const stock = 0; if (stock) { A } else { B }. Which runs?

Question 4

4.What is a guard clause?

Read more (free)

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.

From Operators and conditions

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.

From Decisions: if, else, switch and switch expressions

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

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.

From Booleans and comparisons

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

  1. 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.
  2. Module 2 exam: Strings, decisions and loops · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and closures. 61 topics left in the course before the final exam.

← Previous: Strings and template literals