Welcome back! 👋 In the previous lesson, you learned about JavaScript data types and how variables store different kinds of values. Now it's time to make your programs smart — by teaching them to make decisions!
Conditional statements allow your code to execute different blocks based on whether a condition is true or false. They're the backbone of every meaningful JavaScript program.
Let's dive in and explore all the ways JavaScript lets you control what happens and when!
What are Conditional Statements?
A conditional statement evaluates an expression and runs a specific block of code depending on the result.
Why Conditional Statements Matter
Without conditionals, your program would run the same code every single time — no decisions, no logic, no reactions to user input. Conditionals allow you to:
- Show different content to different users
- Validate form input before submission
- Handle errors gracefully
- Control game logic, permissions, workflows, and much more
Example:
let age = 20;
if (age >= 18) {
console.log("You can vote!"); // This runs
} else {
console.log("Too young to vote."); // This is skipped
}JavaScript's Conditional Tools
JavaScript provides five main ways to write conditional logic:
ifstatement — run code when a condition is trueif...elsestatement — choose between two pathsif...else if...elseladder — handle multiple conditions- Ternary operator (
? :) — one-line shorthand for simple conditions switchstatement — match one value against many cases
Truthy and Falsy Values
Before we dive in, it's important to understand how JavaScript evaluates conditions.
JavaScript doesn't require a strict true or false in a condition — it converts any value to a boolean automatically. These are called truthy and falsy values.
Falsy Values (6 total)
These values evaluate to false in a condition:
false
0
"" // empty string
null
undefined
NaNTruthy Values
Everything else is truthy — including:
"hello" // non-empty string
1 // non-zero number
[] // empty array
{} // empty object
"0" // string "0" is truthy!Example:
let username = "";
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please enter a username."); // This runs — empty string is falsy
}1. The if Statement
The simplest conditional — it runs a block of code only if the condition is truthy.
Syntax
if (condition) {
// code runs only if condition is true
}Example
let temperature = 35;
if (temperature > 30) {
console.log("It's a hot day! Stay hydrated. 🌞");
}
// Output: It's a hot day! Stay hydrated. 🌞let score = 40;
if (score >= 50) {
console.log("You passed!");
}
// No output — condition is false, block is skippedSingle-line if (without braces)
let isLoggedIn = true;
if (isLoggedIn) console.log("Welcome back!"); // Works, but not recommended
// ✅ Always prefer braces — they prevent bugs when adding more lines later
if (isLoggedIn) {
console.log("Welcome back!");
}2. The if...else Statement
Use else to define what should happen when the condition is false.
Syntax
if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}Example
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote. ✅");
} else {
console.log("You are not eligible to vote yet. ❌");
}
// Output: You are not eligible to vote yet. ❌let balance = 500;
let withdrawAmount = 1000;
if (withdrawAmount <= balance) {
console.log("Transaction successful!");
balance -= withdrawAmount;
} else {
console.log("Insufficient balance. Transaction failed.");
}
// Output: Insufficient balance. Transaction failed.3. The if...else if...else Ladder
When you need to check multiple conditions, chain them using else if. JavaScript evaluates each condition top-to-bottom and stops at the first one that is true.
Syntax
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 is false AND condition2 is true
} else if (condition3) {
// runs if condition1 and condition2 are false AND condition3 is true
} else {
// runs if none of the conditions are true
}Example: Grade Calculator
let marks = 72;
if (marks >= 90) {
console.log("Grade: A 🌟");
} else if (marks >= 75) {
console.log("Grade: B 👍");
} else if (marks >= 60) {
console.log("Grade: C 🙂");
} else if (marks >= 40) {
console.log("Grade: D ⚠️");
} else {
console.log("Grade: F ❌ - Please retake the exam.");
}
// Output: Grade: C 🙂Example: Time of Day Greeting
let hour = 14; // 2 PM (24-hour format)
if (hour < 12) {
console.log("Good morning! ☀️");
} else if (hour < 17) {
console.log("Good afternoon! 🌤️");
} else if (hour < 21) {
console.log("Good evening! 🌆");
} else {
console.log("Good night! 🌙");
}
// Output: Good afternoon! 🌤️Important: JavaScript stops checking as soon as it finds a true condition. Once a block executes, the rest are skipped.
let x = 15;
if (x > 5) {
console.log("Greater than 5"); // ✅ This runs
} else if (x > 10) {
console.log("Greater than 10"); // This is NEVER checked — first condition already matched
} else {
console.log("5 or less");
}
// Output: Greater than 54. Ternary Operator
The ternary operator is a compact, one-line version of if...else. It's called "ternary" because it takes three operands.
Syntax
condition ? valueIfTrue : valueIfFalseExample
let age = 20;
// Traditional if...else
let status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
// Same thing with ternary ✅
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"More Examples
let isRaining = true;
let advice = isRaining ? "Take an umbrella ☂️" : "No umbrella needed ☀️";
console.log(advice); // "Take an umbrella ☂️"
// Ternary in template literals
let score = 85;
console.log(`Result: ${score >= 50 ? "Pass ✅" : "Fail ❌"}`);
// Output: Result: Pass ✅
// Ternary for quick value assignment
let num = -7;
let absValue = num >= 0 ? num : -num;
console.log(absValue); // 7Nested Ternary (Use with Caution ⚠️)
let marks = 72;
// ❌ Nested ternary — hard to read
let grade = marks >= 90 ? "A" : marks >= 75 ? "B" : marks >= 60 ? "C" : "F";
// ✅ Better to use if...else for multiple conditionsRule of thumb: Use ternary for simple two-way conditions. Use if...else if for three or more branches.
5. Switch Statement
The switch statement compares one value against multiple possible cases. It's a cleaner alternative to a long if...else if chain when you're matching exact values.
Syntax
switch (expression) {
case value1:
// code if expression === value1
break;
case value2:
// code if expression === value2
break;
default:
// code if no case matches
}Example: Day of the Week
let day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the work week! 💪");
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
console.log("Midweek grind! 📚");
break;
case "Friday":
console.log("Almost the weekend! 🎉");
break;
case "Saturday":
case "Sunday":
console.log("It's the weekend! 😎");
break;
default:
console.log("Invalid day entered.");
}
// Output: Midweek grind! 📚Example: Traffic Light
let signal = "green";
switch (signal) {
case "red":
console.log("Stop 🔴");
break;
case "yellow":
console.log("Get ready 🟡");
break;
case "green":
console.log("Go! 🟢");
break;
default:
console.log("Unknown signal ⚠️");
}
// Output: Go! 🟢The break Keyword
Without break, JavaScript "falls through" to the next case and keeps executing!
let num = 1;
switch (num) {
case 1:
console.log("One");
// ❌ No break — falls through!
case 2:
console.log("Two");
case 3:
console.log("Three");
break;
}
// Output:
// One
// Two
// Three ← Not what we wanted!let num = 1;
switch (num) {
case 1:
console.log("One");
break; // ✅ Stops here
case 2:
console.log("Two");
break;
case 3:
console.log("Three");
break;
}
// Output: One ✅Intentional Fall-Through
Sometimes fall-through is useful — when multiple cases share the same logic:
let month = 4; // April
switch (month) {
case 4:
case 6:
case 9:
case 11:
console.log("This month has 30 days.");
break;
case 2:
console.log("February has 28 or 29 days.");
break;
default:
console.log("This month has 31 days.");
}
// Output: This month has 30 days.Logical Operators in Conditions
You can combine conditions using logical operators to build powerful conditional checks.
&& (AND) — Both must be true
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive! 🚗");
} else {
console.log("You cannot drive.");
}
// Output: You can drive! 🚗|| (OR) — At least one must be true
let isWeekend = false;
let isHoliday = true;
if (isWeekend || isHoliday) {
console.log("No work today! 🎉");
} else {
console.log("Back to work. 💼");
}
// Output: No work today! 🎉! (NOT) — Flips the condition
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in to continue.");
}
// Output: Please log in to continue.Combining Multiple Operators
let age = 22;
let hasTicket = true;
let isBanned = false;
if (age >= 18 && hasTicket && !isBanned) {
console.log("Welcome to the event! 🎟️");
} else {
console.log("Entry denied.");
}
// Output: Welcome to the event! 🎟️Comparison: When to Use What
| Scenario | Best Choice |
|---|---|
| One condition to check | if |
| Two outcomes (true/false) | if...else |
| Multiple ranges or complex conditions | if...else if...else |
| Simple two-outcome assignment in one line | Ternary ? : |
| Matching one variable against exact values | switch |
Common Mistakes with Conditionals
Mistake 1: Using = instead of ===
let x = 10;
// ❌ Wrong — this ASSIGNS 5 to x, not a comparison!
if (x = 5) {
console.log("x is 5"); // Always runs!
}
// ✅ Correct — use === for comparison
if (x === 5) {
console.log("x is 5");
}Mistake 2: Loose Equality (==) vs Strict Equality (===)
// ❌ == converts types before comparing
console.log(0 == false); // true (type coercion!)
console.log("" == false); // true (type coercion!)
console.log(1 == "1"); // true (type coercion!)
// ✅ === checks both value AND type — always prefer this
console.log(0 === false); // false
console.log("" === false); // false
console.log(1 === "1"); // falseMistake 3: Missing break in Switch
// ❌ Forgot break — unintended fall-through
let day = 1;
switch (day) {
case 1:
console.log("Monday");
case 2:
console.log("Tuesday"); // Also prints accidentally!
}
// Output: Monday Tuesday
// ✅ Add break to each case
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
}
// Output: Monday ✅Mistake 4: Overcomplicating with Nested Ternaries
// ❌ Impossible to read at a glance
let result = a > b ? "a is greater" : a < b ? "b is greater" : "they are equal";
// ✅ Much clearer with if...else
if (a > b) {
result = "a is greater";
} else if (a < b) {
result = "b is greater";
} else {
result = "they are equal";
}Practical Exercise: Student Result System
Create a file called conditions-demo.js and try this:
// 🎯 Student Result System
function getStudentResult(name, marks, attendance) {
console.log(`\n=== Result for ${name} ===`);
console.log("Marks:", marks);
console.log("Attendance:", attendance + "%");
// Check attendance first
if (attendance < 75) {
console.log("Result: DETAINED ❌ (Attendance below 75%)");
return;
}
// Check marks using if...else if ladder
if (marks >= 90) {
console.log("Grade: A+ 🌟 | Result: DISTINCTION");
} else if (marks >= 75) {
console.log("Grade: A 🎉 | Result: FIRST CLASS");
} else if (marks >= 60) {
console.log("Grade: B 👍 | Result: SECOND CLASS");
} else if (marks >= 40) {
console.log("Grade: C ✅ | Result: PASS");
} else {
console.log("Grade: F ❌ | Result: FAIL");
}
// Ternary for scholarship check
let scholarship = marks >= 85 && attendance >= 90
? "Eligible for scholarship 🏆"
: "Not eligible for scholarship";
console.log(scholarship);
}
// Test cases
getStudentResult("Mihir", 92, 95);
getStudentResult("Priya", 78, 80);
getStudentResult("Ravi", 55, 70);
getStudentResult("Sara", 45, 60); // Detained
getStudentResult("Arjun", 35, 85);Run it:
node conditions-demo.jsExpected Output:
=== Result for Mihir ===
Marks: 92
Attendance: 95%
Grade: A+ 🌟 | Result: DISTINCTION
Eligible for scholarship 🏆
=== Result for Sara ===
Marks: 45
Attendance: 60%
Result: DETAINED ❌ (Attendance below 75%)Key Takeaways
Congratulations! 🎉 You now understand how to control the flow of your JavaScript programs with conditional statements.
✅ Conditional statements let your code make decisions based on conditions.
✅ Truthy & Falsy:
- Falsy:
false,0,"",null,undefined,NaN - Everything else is truthy
✅ if Statement:
- Runs a block only when condition is true
✅ if...else Statement:
- Two branches — one for true, one for false
✅ if...else if...else Ladder:
- Multiple conditions checked top-to-bottom
- First match wins — rest are skipped
✅ Ternary Operator (? :):
- One-line shorthand for simple
if...else - Best for simple, two-outcome assignments
✅ switch Statement:
- Matches one value against exact cases
- Always use
breakunless fall-through is intentional
✅ Logical Operators:
&&— both conditions must be true||— at least one must be true!— flips the condition
Best Practices
- ✅ Always use
===instead of==in conditions - ✅ Always use
{}braces, even for single-lineifblocks - ✅ Add a
defaultcase in everyswitchstatement - ✅ Always use
breakin switch cases (unless intentional fall-through) - ✅ Keep ternary operators simple — avoid nesting them
- ✅ Put the most likely condition first in an
if...else ifladder - ✅ Use
switchfor exact value matching,if...elsefor range checks - ✅ Never confuse assignment
=with comparison===
What's Next?
Excellent work! 🎉 You now know how to make your JavaScript programs think and decide.
In the next lessons, we'll explore each conditional tool in greater depth:
- If Else Ladder — handling complex real-world conditions step by step
- Ternary Operator — writing cleaner, more concise code
- Switch Case — matching values efficiently with clean syntax
Conditional statements are used in virtually every JavaScript program you'll ever write — from form validation to game logic to API responses. Keep practicing!