
Control Structures in JavaScript: if-else and switch Made Easy!
When you start learning to code in JavaScript, one of the first and most important things you’ll come across is decision-making in programs. Just like we make decisions in real life—whether to eat, sleep, go out, or stay in—JavaScript also needs ways to make choices. That’s where control structures like if-else and switch come into play.
In this blog, we’ll explore both if-else and switch statements in detail. You’ll learn:
- How and when to use if, if-else, if-else-if, and nested if-else.
- How to write a switch statement and use important parts like case, default, and break.
- Real-life examples to help you relate every concept to everyday situations.
Whether you're a complete beginner or someone revising the basics, this blog will make these fundamental concepts crystal clear.
🧠 Why Control Structures?
Imagine you’re building a website, and you want to show different messages based on the time of the day:
- Good Morning 🌅 before 12 PM
- Good Afternoon ☀️ between 12 PM to 6 PM
- Good Evening 🌇 after 6 PM
To make such decisions, your code needs to be able to choose—and that’s where control structures come in.
🌟 JavaScript If-Else Statement
✅ 1. if Statement — Making a Simple Choice
The if statement is like asking a yes or no question. If the answer is yes (true), then the computer does something. If the answer is no (false), it skips that part.
Think of it like this:
“If it is raining, I will carry an umbrella.”
Here, the action (carrying an umbrella) happens only if it is raining. If not, you just walk out without it.
📌 Syntax:
if (condition) {
// code to run if condition is true
}
If the condition is true, the code inside the block runs. If it's false, the block is skipped.
🌍Example 1: Checking if it's Raining
let isRaining = true;
if (isRaining) {
console.log("Take an umbrella!");
}
If isRaining is true, the message “Take an umbrella!” is shown. If it’s not raining, nothing happens.
🌍Example 2: Checking if a user is logged in
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back, user!");
}
If isLoggedIn is true, we greet the user. Otherwise, the greeting doesn't appear.
🔄 2. if-else Statement — Choosing Between Two Options
The if-else statement gives your program two choices:
- Do something if the condition is true.
- Do something else if it’s false.
It’s like:
“If I’m hungry, I’ll eat lunch. Otherwise, I’ll take a nap.”
Here, you’re choosing one out of two options based on your condition.
📌 Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
🌍Example 1: Age Check for Voting
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are not eligible to vote.");
}
If the person is 18 or older, they can vote. Otherwise, they’re told they are not eligible.
🌍Example 2: Check for Pass or Fail
let marks = 45;
if (marks >= 40) {
console.log("Congratulations! You passed the exam.");
} else {
console.log("Unfortunately, you failed the exam.");
}
If marks are 40 or more, the student passes. Otherwise, they fail.
🪜 3. if-else-if Ladder — Choosing From Many Options
The if-else-if ladder is used when you have more than two choices, and you want to check each one in order.
Imagine:
“If it’s Monday, I’ll go to the gym.
Else if it’s Tuesday, I’ll visit grandma.
Else if it’s Wednesday, I’ll go shopping.
Otherwise, I’ll stay home.”
The computer checks each condition one by one from top to bottom. As soon as it finds one that is true, it does that action and ignores the rest.
📌 Syntax:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else if (condition3) {
// code if condition3 is true
} else {
// code if none are true
}
🌍Example 1: Grading System
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
Depending on the value of score, the correct grade is printed. Only one block will execute.
🌍Example 2: Time of Day Greeting
let hour = 15;
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!");
}
This example displays different greetings depending on the time of the day.
🧩 4. Nested if-else — Decision Inside Another Decision
A nested if-else is when you put one decision inside another. This is useful when one decision depends on the result of another.
It’s like:
“If the shop is open,
* If I have money, I’ll buy ice cream.*
* Else, I’ll just look around.*
Else, I’ll go home.”
Here, the second decision (about money) is only made if the first condition (shop is open) is true.
📌 Syntax:
if (condition1) {
if (condition2) {
// code if both condition1 and condition2 are true
} else {
// code if condition1 is true but condition2 is false
}
} else {
// code if condition1 is false
}
🌍Example 1: ATM Withdrawal Check
let isCardInserted = true;
let accountBalance = 1000;
let withdrawalAmount = 500;
if (isCardInserted) {
if (withdrawalAmount <= accountBalance) {
console.log("Transaction successful!");
} else {
console.log("Insufficient balance.");
}
} else {
console.log("Please insert your card.");
}
First, it checks if the card is inserted. Then, it checks if the balance is enough. Two conditions depend on each other.
🌍Example 2: Online Exam Eligibility
let hasRegistered = true;
let hasPaidFee = false;
if (hasRegistered) {
if (hasPaidFee) {
console.log("You can take the exam.");
} else {
console.log("Please pay the fee to proceed.");
}
} else {
console.log("Please register first.");
}
If a student has registered, we check if the fee is paid. If not even registered, we tell them to register.
🌟 JavaScript Switch Statement
🧠 What is a switch Statement?
A switch statement is used when you want to compare one value against many possible options.
It’s like giving a vending machine your choice, and it checks each option until it finds a match and gives you what you asked for.
In simple words:
If the user says ‘Monday’, print ‘Start of the week’.
If they say ‘Friday’, print ‘Weekend is near’.
If nothing matches, print ‘Not a valid day’.
The switch statement checks your input and chooses the matching block of code to run.
🔹 1. Basic switch Statement
📘 Syntax:
switch(expression) {
case value1:
// code block
break;
case value2:
// code block
break;
// more cases...
}
Here:
- expression is the value we’re checking (like a variable).
- case is each possible value we want to compare with.
- If it matches, the code in that block runs.
🌍Example 1: Day of the Week
let day = "Tuesday";
switch(day) {
case "Monday":
console.log("It's the start of the week!");
break;
case "Tuesday":
console.log("It's a productive Tuesday.");
break;
case "Friday":
console.log("Yay! Weekend is near.");
break;
}
The value of day is "Tuesday", so it matches the second case and prints the message for Tuesday.
🌍Example 2: Choosing a Drink
let drink = "Coffee";
switch(drink) {
case "Tea":
console.log("You chose Tea.");
break;
case "Coffee":
console.log("You chose Coffee.");
break;
case "Juice":
console.log("You chose Juice.");
break;
}
The value "Coffee" matches the second case, so the message “You chose Coffee.” is printed.
🧠 What is default in switch?
The default is used when none of the cases match.
👉 Think of it as a backup option.
If your choice doesn't match anything on the list, the program follows the default instruction.
Just like a vending machine:
- If you press a valid number (like 1, 2, 3), it gives you a snack.
- But if you press a wrong number (like 0), it says “Invalid choice.”
- That “Invalid choice” message is like the default.
🔹 2. The default Case
📘 Syntax with default:
switch(expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no case matches
}
🌍Example 1: Weather Forecast
let weather = "Storm";
switch(weather) {
case "Sunny":
console.log("Wear sunglasses!");
break;
case "Rainy":
console.log("Carry an umbrella.");
break;
default:
console.log("Weather data not available.");
}
Since "Storm" doesn’t match any case, the default block runs and shows a general message.
🌍Example 2: Mobile Recharge Options
let rechargeAmount = 199;
switch(rechargeAmount) {
case 99:
console.log("1GB Data for 18 Days.");
break;
case 249:
console.log("2GB/day for 28 Days.");
break;
default:
console.log("Invalid recharge amount.");
}
Since 199 doesn't match any given cases, the default message helps tell the user it's an invalid option.
🧠 What is break in switch?
The break tells the computer to stop checking further options once a match is found.
👉 Without break, the program continues checking the next options even after finding the correct one.
This can lead to wrong or extra actions being performed.
So, break is like telling the computer:
“You found what you needed — stop right there!”
🔹 3. Importance of the break Statement
The break statement stops the switch from continuing once a matching case has been found.
If you don’t use break, JavaScript will continue checking and running the next cases, even if a match was already found. This is called fall-through and can cause unwanted behavior.
🌍Example 1: Without break
let fruit = "Apple";
switch(fruit) {
case "Apple":
console.log("You chose Apple.");
case "Banana":
console.log("You chose Banana.");
case "Orange":
console.log("You chose Orange.");
}
🧠 Output:
You chose Apple.
You chose Banana.
You chose Orange.
Even though the match was found with “Apple”, all the remaining messages are printed because there are no break statements.
🌍Example 2: With break
let fruit = "Apple";
switch(fruit) {
case "Apple":
console.log("You chose Apple.");
break;
case "Banana":
console.log("You chose Banana.");
break;
case "Orange":
console.log("You chose Orange.");
break;
}
🧠 Output:
You chose Apple.
Now only the correct message is printed, thanks to the break.
🧠 What is Fall-Through in switch?
If you don’t use break, the program will not stop after finding a match.
It will keep checking the next cases and might run more code than needed.
This is called fall-through, and it usually causes errors unless done intentionally.
👉 It’s like:
You choose “Pizza”, but the waiter brings pizza, burger, and fries — just because you didn’t say “Stop” after pizza.
🧠 Final Thoughts
Understanding how to use if-else and switch statements is a foundational step in your JavaScript journey. These control structures are like the decision-makers of your code — helping it respond to different situations intelligently.
Use if-else when your conditions involve comparisons, ranges, or logic. Use switch when you're checking one value against many fixed options. Both tools are equally powerful, and with practice, you’ll know exactly when to use which one.
Keep practicing with small challenges like greeting apps, grading systems, or menu selectors. The more you use these concepts, the more confident you'll feel writing real-world JavaScript programs.
Stay curious, stay consistent — and let your code do the thinking! 💻🚀
Happy Coding!!
5 Reactions
0 Bookmarks