
Understanding Conditional Statements in JavaScript (if, else, switch) | SBT
Conditional statements are a key part of how JavaScript programs make decisions. They help your code choose what to do based on different situations—like a fork in the road where the program decides which direction to take. This is known as control flow, and it’s essential for making your applications dynamic and responsive.
In simple terms, conditional statements check if something is true or false, and then run different blocks of code depending on the result. This allows your program to react to user input, display or hide elements, verify login status, or perform specific actions in a game or app.
JavaScript gives us a few powerful tools for writing these decisions: if, else, else if, and switch. Each one is useful in different situations, but all serve the same purpose—to make your code flexible and interactive.
Understanding how and when to use these statements is an important step in becoming a confident JavaScript developer. Whether you're building a small form or a large application, conditional logic will always play a central role in how your code behaves.
1. The if Statement in JavaScript
The if statement is one of the most basic and important tools in JavaScript. It allows your code to make a decision based on a condition. If the condition is true, a specific block of code will run. If the condition is false, the code inside the if block will be skipped.
Think of it like a gate. The gate only opens (runs the code) if a rule (the condition) is satisfied. If not, the code behind the gate is never reached.
Let’s start with a simple example:
let age = 18; if (age >= 18) { console.log("You are eligible to vote."); }
In this example, the condition age >= 18 checks whether the value of age is greater than or equal to 18. Since age is 18, the condition is true, so the message "You are eligible to vote." is printed. If age had been 17, nothing would have been printed because the condition would be false, and the code inside the if block would not execute.
Now, let’s take an example with a name:
let name = "Sudip"; if (name === "Sudip") { console.log("Welcome, Sudip! You have admin access."); }
Here, we check if the value of the variable name is equal to "Sudip". If the condition is true, it prints a personalized welcome message. If the name was something else, like "Mona Darlo", the condition would be false, and nothing would happen.
Let’s try the same logic with "Mona Darlo":
let userName = "Mona Darlo"; if (userName === "Mona Darlo") { console.log("Hello Mona Darlo! Access granted to premium features."); }
In this case, if the userName is "Mona Darlo", the program prints a message that gives access to some special features. Again, this only happens if the condition is met.
Now let’s look at a slightly more complex example using numbers and logic:
let marks = 82; if (marks >= 90) { console.log("Grade: A+"); } if (marks >= 80 && marks < 90) { console.log("Grade: A"); } if (marks >= 70 && marks < 80) { console.log("Grade: B"); }
This example checks a student’s score stored in the marks variable. It evaluates different conditions to determine the grade. Since marks is 82, only the second condition marks >= 80 && marks < 90 is true, so it prints "Grade: A". The other conditions are false, so their blocks are skipped.
This shows how you can use multiple if statements to handle more detailed conditions. Notice that we didn’t use else here. You can use multiple if statements like this when the conditions are not directly connected or when you want to check multiple things independently.
Here’s one more example that checks both name and age:
let name = "Sudip"; let age = 25; if (name === "Sudip" && age >= 18) { console.log("Sudip is an adult and can vote."); }
In this case, the if statement checks two conditions together using the && (AND) operator. Both must be true for the code inside to run. Since Sudip is 25 and over 18, the message is displayed.
2. The if...else Statement in JavaScript
The if...else statement is a natural extension of the basic if statement. It allows your program to choose between two different paths based on whether a condition is true or false. If the condition is true, the if block runs. If the condition is false, the code inside the else block runs instead. This gives your program the ability to respond appropriately in either case.
Let’s start with a simple example:
let age = 16; if (age >= 18) { console.log("You can vote."); } else { console.log("You are not eligible to vote yet."); }
In this example, the program checks whether the value of age is greater than or equal to 18. Since age is 16, the condition is false. As a result, the code inside the else block is executed, and it prints: "You are not eligible to vote yet." If the value of age had been 18 or higher, the program would have printed: "You can vote."
Let’s look at another example that uses your name, Sudip:
let userName = "Sudip"; if (userName === "Sudip") { console.log("Welcome back, Sudip!"); } else { console.log("User not recognized."); }
Here, the program checks if the user's name is "Sudip". If it matches, it prints a personalized welcome message. Otherwise, it responds with "User not recognized." This is a useful pattern when you're validating identity, access, or role in an application.
Use === for strict comparison (checks value and type), while == performs loose comparison (converts types before checking). Always prefer === to avoid unexpected results.
Now, let’s try an example with Mona Darlo:
let name = "Mona Darlo"; if (name === "Mona Darlo") { console.log("Hello, Mona Darlo! Your dashboard is ready."); } else { console.log("Guest user detected. Limited access granted."); }
This example shows a common real-world situation where a system might personalize the experience for a known user and give limited options to unknown or guest users. If the name is "Mona Darlo", a friendly message is shown. Otherwise, the program falls back to a default response.
Now let’s see a slightly more complex example using numbers and calculations:
let score = 47; if (score >= 50) { console.log("Congratulations, you passed the exam."); } else { console.log("Unfortunately, you did not pass. Please try again."); }
In this case, the condition checks if the score is 50 or more. If it is, the student passes. If not, the else block delivers a different message. This kind of logic is very common in educational apps, result processing systems, and online tests.
Let’s now take it a step further by combining name and age in a single condition:
let user = "Sudip"; let userAge = 17; if (user === "Sudip" && userAge >= 18) { console.log("Sudip is eligible for a driver's license."); } else { console.log("Sudip is not yet eligible for a driver's license."); }
Here, we’re checking two conditions at the same time: whether the user is "Sudip" and whether their age is 18 or above. If both conditions are true, the if block runs. If even one is false, the else block runs. In this example, the age is 17, so the second condition fails, and the output will be: "Sudip is not yet eligible for a driver's license."
3. The if...else if...else Ladder in JavaScript
When you need to check more than two conditions, using just if and else isn't enough. That’s where the if...else if...else ladder becomes very useful. It lets you test multiple conditions one by one, from top to bottom, until it finds one that’s true. Once a true condition is found, JavaScript runs that block of code and skips the rest.
Let’s start with a basic example using exam marks:
let marks = 75; if (marks >= 90) { console.log("Grade: A"); } else if (marks >= 75) { console.log("Grade: B"); } else if (marks >= 50) { console.log("Grade: C"); } else { console.log("Grade: F"); }
In this case, the program checks the value of marks one step at a time:
- First, it checks if marks >= 90. That’s false.
- Then it checks if marks >= 75. That’s true.
- So it prints "Grade: B" and stops there.
Even though the third condition (marks >= 50) is also true, JavaScript ignores it because it already found a match.
Now let’s see a similar example involving your name, Sudip, and custom messages based on your access level:
let role = "admin"; if (role === "owner") { console.log("Welcome Sudip! You have full control."); } else if (role === "admin") { console.log("Hello Sudip! You have admin privileges."); } else if (role === "editor") { console.log("Hi Sudip! You can edit content."); } else { console.log("Welcome Sudip! You are logged in as a viewer."); }
Here, the role is checked one by one. Since role is "admin", the program prints "Hello Sudip! You have admin privileges." and skips the rest. If Sudip's role had been "editor", the program would have printed a different message.
Now let’s write an example for Mona Darlo, showing how a program might welcome users based on membership tier:
let memberType = "premium"; if (memberType === "platinum") { console.log("Mona Darlo, you get unlimited access and VIP support."); } else if (memberType === "premium") { console.log("Welcome back, Mona Darlo! Enjoy your premium features."); } else if (memberType === "basic") { console.log("Hello Mona Darlo! Upgrade to premium for more benefits."); } else { console.log("Welcome guest! Sign up for full access."); }
Again, only the condition that matches ("premium") will be executed. Even if other conditions could match in theory, only the first true one is considered.
Now let’s explore a more complex example using numbers and logic—this time, grading students based on marks and giving extra feedback.
let marks = 91; if (marks >= 90) { console.log("Grade: A"); console.log("Excellent job, Sudip! You’ve scored above 90."); } else if (marks >= 75) { console.log("Grade: B"); console.log("Well done, Sudip. Keep aiming higher."); } else if (marks >= 50) { console.log("Grade: C"); console.log("Good effort, Sudip. You can improve with practice."); } else { console.log("Grade: F"); console.log("Don’t give up, Sudip. Study harder next time."); }
In this example, we’re not only assigning a grade based on marks but also giving a custom message with it. Since the value of marks is 91, the first condition is true. So the program prints "Grade: A" followed by a motivational message. The rest of the conditions are skipped.
4. The switch Statement in JavaScript
The switch statement is another way to handle decision-making in JavaScript. It's especially useful when you want to compare one variable against multiple possible values. Instead of writing several if...else if conditions, switch offers a cleaner and more organized structure, particularly when all comparisons are based on the same variable.
Let’s start with a basic example using days of the week:
let day = 3; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; case 4: console.log("Thursday"); break; default: console.log("Invalid day"); }
In this example, the value of day is compared against several predefined cases. Since day is 3, it matches case 3, and "Wednesday" is printed. The break statement ensures that the program stops checking other cases once a match is found. Without it, the code would continue running the next cases too, which usually isn’t what you want. If none of the cases match the variable, the default block runs, printing "Invalid day".
Now let’s look at a fun example using your name, Sudip, and switch logic to display personalized roles:
let userRole = "admin"; switch (userRole) { case "owner": console.log("Welcome Sudip! You have full system access."); break; case "admin": console.log("Hello Sudip! You can manage users and settings."); break; case "editor": console.log("Sudip, you can create and update content."); break; default: console.log("Hi Sudip! You have basic access."); }
In this scenario, if the userRole is "admin", the switch statement prints: "Hello Sudip! You can manage users and settings." Just like before, the first match stops further evaluation because of the break statement.
Now let’s create a similar example for Mona Darlo, where different membership levels give different benefits:
let membership = "premium"; switch (membership) { case "platinum": console.log("Mona Darlo, enjoy unlimited features and top-tier support."); break; case "premium": console.log("Mona Darlo, your premium access is active. Enjoy your benefits."); break; case "basic": console.log("Mona Darlo, consider upgrading to unlock more features."); break; default: console.log("Welcome guest! Sign in to access more features."); }
Here, the membership variable is checked against different levels. When it's "premium", the matching block prints a personalized message for Mona Darlo. This is a practical way to manage different user tiers or settings in real applications.
Let’s now explore a more complex example involving numbers and feedback based on scores, using a combination of logic and rounding:
let score = 87; let grade = Math.floor(score / 10); // This gives us 8 for scores between 80-89 switch (grade) { case 10: case 9: console.log("Excellent! Grade: A"); break; case 8: console.log("Very Good! Grade: B"); break; case 7: console.log("Good Job! Grade: C"); break; case 6: console.log("You passed. Grade: D"); break; default: console.log("Failed. Grade: F"); }
In this version, we divide the score by 10 and use Math.floor() to get a simplified number (like 8 for anything between 80–89). This allows us to group scores and assign grades efficiently. Since score is 87, the grade becomes 8, and the program prints "Very Good! Grade: B".
Concluding
Your JavaScript code can respond to input, make decisions, and adjust to changing circumstances thanks to conditional statements. Your applications' logical control flow is built on top of the if, else, and switch statements. Writing interactive and intelligent code requires knowing these statements, whether you're responding to events, grading user input, or checking user input.
0 Comments