JavaScript Conditions: if, else, switch and Ternary
Learn to make decisions in JavaScript with if, else if, else, switch and the ternary operator, plus truthy and falsy values, using real examples.
What you will learn
Until now, your code ran every line from top to bottom. Real programs need to decide: “If the user is 18 or older, allow entry. Otherwise, show a message.” These decisions are made with conditions. In this lesson you will learn if, else if and else, nested conditions, the switch statement, the short ternary operator, and how truthy and falsy values work inside conditions.
Decisions in real life
You make decisions all the time:
- If it is raining, take an umbrella. Otherwise, wear sunglasses.
- If the balance is enough, pay. Else if you have a credit card, use that. Otherwise, cancel.
JavaScript lets you write exactly this. A condition is an expression that gives true or false, usually made with the comparison and logical operators you already know.
The if statement
const age = 20;
if (age >= 18) {
console.log("You can vote.");
}
Output:
You can vote.
How it works:
- JavaScript checks the condition in the brackets:
age >= 18. - If it is
true, the code inside{ }runs. - If it is
false, the block is skipped.
Change age to 15 and nothing prints.
Tip: Always use curly braces
{ }and indent the code inside. JavaScript allowsif (x) doSomething();without braces, but it causes bugs when you add more lines later.
if ... else
Use else for the “otherwise” case. Exactly one of the two blocks runs.
const age = 15;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are too young to vote.");
}
Output:
You are too young to vote.
else if: more than two choices
When there are several possibilities, chain them with else if:
const marks = 82;
if (marks >= 90) {
console.log("Grade: A+");
} else if (marks >= 75) {
console.log("Grade: A");
} else if (marks >= 60) {
console.log("Grade: B");
} else if (marks >= 40) {
console.log("Grade: C");
} else {
console.log("Grade: Fail");
}
Output:
Grade: A
JavaScript checks the conditions from top to bottom, runs the first one that is true, and skips the rest. That is why order matters. Look what happens if you put the easiest check first:
const marks = 95;
if (marks >= 40) {
console.log("Grade: C"); // runs, and everything below is skipped
} else if (marks >= 90) {
console.log("Grade: A+"); // never reached
}
A mark of 95 gets a C. Always put the most specific condition first.
Conditions with logical operators
Combine questions with && (and), || (or) and ! (not):
const age = 25;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Welcome to the show!");
}
const day = "Sunday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
}
const isBanned = false;
if (!isBanned) {
console.log("Access allowed.");
}
Truthy and falsy in conditions
A condition does not have to be a comparison. JavaScript converts any value to true or false (you saw this in the coercion lesson). The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy.
This makes checks very short:
const username = "";
if (username) {
console.log("Hello, " + username);
} else {
console.log("Please enter your username");
}
Output:
Please enter your username
Common short checks:
const username = "";
const items = [];
const cart = ["shirt", "shoes"];
if (!username) { console.log("Username is empty"); } // empty text
if (cart.length) { console.log("Cart has items"); } // 2 is truthy
if (items.length === 0) { console.log("No items"); } // clearer for lists
The trap: when 0 is a real value
const score = 0;
if (score) {
console.log("Score is " + score);
} else {
console.log("No score"); // runs, but 0 IS a valid score!
}
Here the person scored zero, but the check says “no score”. When 0 or "" are valid values, be exact:
const score = 0;
if (score !== undefined && score !== null) {
console.log("Score is " + score); // "Score is 0"
}
Also remember that an empty array [] and empty object {} are truthy. Check .length to test an array.
Nested conditions
You can put an if inside another if:
const age = 20;
const hasId = true;
if (age >= 18) {
if (hasId) {
console.log("Entry allowed.");
} else {
console.log("Please show your ID.");
}
} else {
console.log("Too young to enter.");
}
It works, but too many levels are hard to read (people call it the “pyramid of doom”). Two simple ways to keep code flat:
1. Combine conditions with &&:
const age = 20;
const hasId = true;
if (age >= 18 && hasId) {
console.log("Entry allowed.");
}
2. Handle the “bad” cases first (early checks):
const age = 20;
const hasId = true;
if (age < 18) {
console.log("Too young to enter.");
} else if (!hasId) {
console.log("Please show your ID.");
} else {
console.log("Entry allowed.");
}
Rule of thumb: if you are nesting more than two levels deep, rewrite it flatter.
The switch statement
When you compare one value against many exact options, switch can be cleaner than a long else if chain.
const day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Another day";
}
console.log(dayName); // "Wednesday"
How it works:
- JavaScript evaluates
dayonce, then jumps to the firstcasethat matches exactly (it uses===). breakstops the switch. Without it, the code keeps running into the next case (called fall-through).defaultruns if nothing matches. It is likeelse.
Forgetting break
const day = 1;
switch (day) {
case 1:
console.log("Monday");
case 2:
console.log("Tuesday");
default:
console.log("Other");
}
Output:
Monday
Tuesday
Other
All three lines ran because there is no break. This is the most common switch mistake.
Grouping cases on purpose
Fall-through is useful when several cases should do the same thing:
const day = 6;
switch (day) {
case 6:
case 7:
console.log("Weekend!");
break;
case 1:
case 2:
case 3:
case 4:
case 5:
console.log("Weekday");
break;
default:
console.log("Invalid day");
}
switch uses strict comparison
const value = "5";
switch (value) {
case 5:
console.log("number 5");
break;
case "5":
console.log("text 5"); // this one matches
break;
}
case 5 does not match "5", because switch uses ===.
A small calculator
const a = 10;
const b = 5;
const operator = "*";
switch (operator) {
case "+":
console.log(a + b);
break;
case "-":
console.log(a - b);
break;
case "*":
console.log(a * b); // 50
break;
case "/":
console.log(a / b);
break;
default:
console.log("Unknown operator");
}
if or switch?
Use if / else if when |
Use switch when |
|---|---|
You check ranges (marks >= 90) |
You check exact values ("+", 1, "admin") |
| Conditions are different questions | Everything compares one value |
| There are 2 or 3 choices | There are many choices |
The ternary operator
The ternary operator is a one-line if / else that gives back a value. It is the only JavaScript operator with three parts:
condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
That is the same as:
const age = 20;
let status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
It is perfect for small choices, especially inside template literals:
const count = 1;
console.log(`You have ${count} item${count === 1 ? "" : "s"} in your cart.`);
// "You have 1 item in your cart."
const isOnline = true;
console.log(`Status: ${isOnline ? "🟢 Online" : "⚪ Offline"}`);
You can chain ternaries, but it becomes hard to read quickly:
const marks = 82;
const grade = marks >= 90 ? "A+" : marks >= 75 ? "A" : marks >= 40 ? "B" : "Fail";
console.log(grade); // "A"
Tip: Use a ternary for one simple choice. If you need more than one
? :, useif / else if. Do not use a ternary to run actions. It is meant to produce a value.
Short-circuit conditions (bonus)
&& and || can act like small if statements:
const isLoggedIn = true;
isLoggedIn && console.log("Welcome back!"); // runs only if isLoggedIn is truthy
const nickname = "";
const name = nickname || "Guest"; // fallback value
console.log(name); // "Guest"
This is common in real code, but for actions a normal if is easier to read. Use short-circuiting mainly for default values.
Real-life use cases
1. Ticket price by age
const age = 8;
let price;
if (age < 5) {
price = 0;
} else if (age <= 12) {
price = 100;
} else if (age >= 60) {
price = 150;
} else {
price = 300;
}
console.log(`Ticket price: ₹${price}`); // "Ticket price: ₹100"
2. Login form check
const username = "riya";
const password = "abc";
if (username.trim() === "" || password === "") {
console.log("Please fill in all fields.");
} else if (password.length < 6) {
console.log("Password must be at least 6 characters.");
} else {
console.log("Logging in...");
}
Output:
Password must be at least 6 characters.
3. Leap year
A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400.
const year = 2024;
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log(year + " is a leap year");
} else {
console.log(year + " is not a leap year");
}
Try 1900 (not a leap year) and 2000 (a leap year).
4. Free shipping and discount
const cartTotal = 1200;
const hasCoupon = true;
let discount = 0;
if (hasCoupon && cartTotal >= 1000) {
discount = 100;
}
const shipping = cartTotal >= 999 ? 0 : 49;
const finalAmount = cartTotal - discount + shipping;
console.log(`Pay ₹${finalAmount}`); // "Pay ₹1100"
5. Greeting by the time of day
const hour = new Date().getHours(); // 0 to 23 (you will learn Date later)
let greeting;
if (hour < 12) {
greeting = "Good morning";
} else if (hour < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
console.log(greeting + "!");
6. Validating a number typed by the user
const input = "25";
const age = Number(input);
if (input.trim() === "" || Number.isNaN(age)) {
console.log("Please enter a valid number.");
} else if (age < 0 || age > 120) {
console.log("Please enter a realistic age.");
} else {
console.log("Thanks! Your age is " + age);
}
7. Traffic light with switch
const light = "yellow";
switch (light) {
case "red":
console.log("Stop");
break;
case "yellow":
console.log("Get ready");
break;
case "green":
console.log("Go");
break;
default:
console.log("Broken traffic light!");
}
Common mistakes
- Using
=instead of===in a condition.if (age = 18)assigns 18 and is always truthy. Use===. - Putting a semicolon right after the condition.
if (age > 18);ends theifimmediately, and the block below always runs. - Writing half the condition.
if (day === "Sat" || "Sun")is always true. Writeday === "Sat" || day === "Sun". - Chained comparison.
if (18 < age < 60)does not work like in maths. Writeage > 18 && age < 60. - Wrong order in an
else ifladder. Check the most specific or highest condition first. - Forgetting
breakinswitch. The code falls into the next case. - Expecting
switchto match"5"and5. It uses===. - Declaring the same
letin two cases. Wrap each case body in{ }if you need its own variables. - Comparing text numbers.
"10" > "9"isfalse. Convert input withNumber()first. - Treating
0or""as “no value”. Use exact checks when they are valid. - Nested ternaries everywhere. Use
if / else ifonce they get long.
Practice
-
Write a program with
const number = ...that prints whether the number is positive, negative or zero. -
Print whether a number is even or odd using
%and a ternary operator. -
Create
const temperature = .... Print “Freezing” below 0, “Cold” up to 15, “Pleasant” up to 30, and “Hot” above that. -
Write a
switchthat takes a number from 1 to 7 and prints the name of the weekday. Usedefaultfor other numbers. -
A cinema allows entry if the person is 18 or older and has a ticket, or if they are with a parent (
withParent). Write the condition and test all combinations. -
Use the leap year code with the years
1900,2000,2023and2024. Predict each result first. -
Rewrite this nested code as a flat condition:
if (isLoggedIn) { if (hasPaid) { console.log("Show course"); } } -
Challenge: build a simple rock-paper-scissors judge. Given
playerandcomputer(each"rock","paper"or"scissors"), print"Draw","You win"or"You lose".
Recap
- Conditions let a program choose what to run. A condition is any expression, and JavaScript treats it as
trueorfalse. - Use
if,else ifandelse. Conditions are checked top to bottom and the first true one wins, so order matters. - Combine checks with
&&,||and!. Use===for equality and never=. - Truthy/falsy: the 8 falsy values are
false,0,-0,0n,"",null,undefined,NaN. Everything else is truthy, even[]and{}. Be exact when0or""are valid values. - Keep nesting shallow: combine conditions or check bad cases first.
switchcompares one value with exact (===) cases. Usebreakto stop, anddefaultfor everything else.- The ternary
condition ? a : bis a one-line choice that gives a value. Use it for simple choices only. - Next you will learn loops, which repeat code so you do not have to write it again and again.