Every program makes decisions. if, else, switch, and the ternary operator are the tools JavaScript gives you to control exactly what happens and when.
Day 11 / 180
Beginner Phase
🕐12 min read
💻6 code examples
🎯3 practice tasks
Every single app you have ever used makes thousands of decisions per second:
🔐 Is the password correct? → Show dashboard or show error
🛒 Is the cart empty? → Show checkout or show "add items"
🌙 Is it night time? → Enable dark mode or light mode
💰 Is balance enough? → Process payment or decline
Without conditional statements your code would run the same way every single time — it could never react to data, user input, or real-world situations. Conditionals are what transform a static script into an intelligent, responsive program.
JavaScript gives you four tools for making decisions: if, else if, else, the ternary operator, and switch. By the end of this lesson you will know exactly which one to use in every situation.
1. What is a Conditional Statement?
A conditional statement tells JavaScript: "if this is true — do this. Otherwise — do that." It is the most fundamental concept in all of programming. Every language has it. In JavaScript it looks like this:
JavaScript — Basic Structure
// Basic structureif (condition) {
// runs if condition is true
} else {
// runs if condition is false
}
// Real exampleconst isRaining = true;
if (isRaining) {
console.log("Take an umbrella!");
} else {
console.log("Enjoy the sunshine!");
}
// Take an umbrella!
💡 The condition must evaluate to truthy or falsy. It does not have to be a strict boolean — any expression works. if (username) checks if username is not empty. if (age) checks if age is not 0. JavaScript automatically converts the condition to boolean.
2. if / else — The Foundation
The if statement is the most basic decision tool. The else block is optional — use it only when you need to handle the false case:
JavaScript — if / else
// if only — no else neededconst score = 85;
if (score >= 90) {
console.log("A+ Grade!");
}
// nothing prints — condition was false// if / else — handle both casesconst age = 17;
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("Too young to vote.");
}
// Too young to vote.// Real world — login checkconst username = "waheed";
const password = "1234";
const correctPassword = "pakistan123";
if (password === correctPassword) {
console.log(`Welcome back, ${username}!`);
} else {
console.log("Wrong password. Try again.");
}
// Wrong password. Try again.
3. else if — Multiple Conditions
When you have more than two possible outcomes use else if to chain multiple conditions. JavaScript checks them in order — the first one that is true runs and the rest are skipped:
JavaScript checks conditions top to bottom and stops at the first true one. Always put the most specific condition first. In the grade example — put 90+ before 80+ before 70+. If you reverse the order every mark above 50 would get grade D because marks >= 50 would match first.
Pro Tip #2 — else is always optional
You do not always need an else block. If none of your conditions match and there is no else — nothing happens and JavaScript simply moves on. Only add else when you genuinely need to handle the "none of the above" case.
Pro Tip #3 — Avoid deeply nested if statements
Nesting if inside if inside if creates "pyramid of doom" — code that is impossible to read. If you have more than 3 levels of nesting consider using early returns, switch statements, or lookup objects instead. Flat code is always better than deeply nested code.
4. Ternary Operator — One Line if/else 🔥
The ternary operator is a shorthand for simple if/else — it fits on one line. You will see it everywhere in React and modern JavaScript. The syntax is: condition ? valueIfTrue : valueIfFalse:
JavaScript — Ternary Operator
// if/else — verboselet message;
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
// Ternary — same result, one line ✅const message = age >= 18 ? "Adult" : "Minor";
// Real world usesconst isLoggedIn = true;
const greeting = isLoggedIn ? "Welcome back!" : "Please login";
console.log(greeting); // "Welcome back!"const score = 75;
const result = score >= 50 ? "Pass ✅" : "Fail ❌";
console.log(result); // "Pass ✅"// In template literalsconst stock = 0;
console.log(`Item is ${stock > 0 ? "available" : "out of stock"}`);
// Item is out of stock// Nested ternary — use sparingly!const marks2 = 85;
const grade = marks2 >= 90 ? "A+"
: marks2 >= 80 ? "A"
: marks2 >= 70 ? "B"
: "C";
console.log(grade); // "A"
5. switch — Clean Multiple Choice
When you are comparing one variable against many possible values — switch is cleaner than a long chain of else if. It uses strict equality for matching:
JavaScript — switch Statement
const day = "Monday";
switch (day) {
case"Monday":
console.log("Start of work week");
break;
case"Friday":
console.log("Almost weekend!");
break;
case"Saturday":
case"Sunday":
console.log("Weekend!"); // handles both Sat and Sunbreak;
default:
console.log("Regular weekday");
}
// Start of work week// Real world — language selectorconst lang = "ur";
let greeting;
switch (lang) {
case"en": greeting = "Hello!"; break;
case"ur": greeting = "Assalam o Alaikum!"; break;
case"ar": greeting = "Marhaba!"; break;
default: greeting = "Hi!";
}
console.log(greeting); // Assalam o Alaikum!
🔥 Never forget break! Without break JavaScript "falls through" to the next case and keeps running. This causes a very common bug where multiple cases execute when only one should. Always end each case with break — unless you deliberately want fall-through behavior.
6. Truthy / Falsy in Conditions — Real Power
You do not always need === true in your conditions. JavaScript automatically converts any value to boolean when used in an if statement. This leads to much cleaner, more readable code:
JavaScript — Truthy/Falsy in Conditions
// Checking if a value existsconst username = "Waheed";
// Verbose wayif (username !== "" && username !== null && username !== undefined) {}
// Clean way ✅if (username) {
console.log(`Hello, ${username}!`);
}
// Checking array has itemsconst items = ["apple", "banana"];
if (items.length) {
console.log(`${items.length} items in cart`);
}
// Checking object exists before accessingconst user = { name: "Waheed" };
if (user && user.name) {
console.log(`Welcome, ${user.name}!`);
}
// These are ALL falsy — fail the if checkif (0) {} // never runsif ("") {} // never runsif (null) {} // never runsif (undefined) {} // never runsif (false) {} // never runsif (NaN) {} // never runs
7. Try It Yourself
Edit the code and click Run Code. Try changing the values to see different branches execute!
✏️ Try it Yourself — Conditional Statements
OUTPUT
// Click Run Code to see output
💡 Edit the code and click Run!
8. Practice Tasks
Task 1 — Easy: Age Checker
Write a program that checks a person's age and prints: "Child" (under 13), "Teenager" (13-17), "Adult" (18-64), or "Senior" (65+). Test it with at least 4 different age values.
Task 2 — Medium: Traffic Light System
Build a traffic light using switch. The variable light can be "red", "yellow", or "green". Print the correct action for each: "Stop!", "Get Ready", "Go!". Use the ternary operator to also check if a car should brake = true or brake = false.
Task 3 — Hard: Simple ATM
Build a simple ATM logic. Variables: balance = 50000, withdrawAmount = 15000, pin = 1234, enteredPin = 1234. Check: is pin correct? Is withdraw amount greater than 0? Is balance enough? Only process withdrawal if ALL conditions pass using &&. Print the remaining balance or specific error message for each failure case.