JavaScript Conditional Statements
Conditional statements allow a program to make decisions. Based on whether a condition is true or false, different blocks of code are executed. This is the foundation of logic in any program.
Real-life analogy: "If it is raining, take an umbrella. Otherwise, wear sunglasses."
The if Statement
The if statement runs a block of code only when the specified condition is true.
Syntax:
if (condition) {
// Code runs if condition is true
}let temperature = 38;
if (temperature > 35) {
console.log("It is very hot today.");
}
// Output: It is very hot today.If the condition is false, the block is simply skipped and the program continues.
The if...else Statement
The else block provides an alternative action when the condition is false.
let marks = 45;
if (marks >= 50) {
console.log("Congratulations! You passed.");
} else {
console.log("Better luck next time. You failed.");
}
// Output: Better luck next time. You failed.The if...else if...else Statement
When there are multiple conditions to check, else if is used to chain them together. JavaScript checks each condition from top to bottom and runs the first one that is true.
let score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else if (score >= 60) {
console.log("Grade: C");
} else if (score >= 50) {
console.log("Grade: D");
} else {
console.log("Grade: F - Failed");
}
// Output: Grade: CNested if Statements
An if statement can be placed inside another if statement. This is called nesting. Use it when a condition depends on another condition being true first.
let age = 20;
let hasTicket = true;
if (age >= 18) {
if (hasTicket) {
console.log("Access granted. Enjoy the event!");
} else {
console.log("Please purchase a ticket first.");
}
} else {
console.log("Sorry, this event is for adults only.");
}
// Output: Access granted. Enjoy the event!The switch Statement
The switch statement is a cleaner alternative to long if...else if chains when checking a single variable against multiple possible values.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week!");
break;
case "Friday":
console.log("Almost the weekend!");
break;
case "Saturday":
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("It's a regular weekday.");
}
// Output: Start of the work week!The break Keyword
The break statement stops execution inside the switch block. Without it, JavaScript continues executing the next case regardless of a match — this is called "fall-through."
let fruit = "Apple";
switch (fruit) {
case "Apple":
console.log("Apple selected");
// No break — falls through to next case!
case "Mango":
console.log("Mango selected");
break;
case "Orange":
console.log("Orange selected");
break;
}
// Output:
// Apple selected
// Mango selected ← unintended fall-through!The default Case
The default block runs when no case matches. It acts like the else in an if/else chain.
let color = "Purple";
switch (color) {
case "Red":
console.log("Red is selected");
break;
case "Blue":
console.log("Blue is selected");
break;
default:
console.log("Color not recognized.");
}
// Output: Color not recognized.Ternary Operator (Short Conditional)
The ternary operator is the most compact way to write a simple if/else. It is useful when assigning a value based on a condition.
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // AdultLogical Operators in Conditions
Logical operators are used to combine multiple conditions within an if statement.
AND (&&) — Both conditions must be true
let username = "admin";
let password = "1234";
if (username === "admin" && password === "1234") {
console.log("Login successful!");
} else {
console.log("Invalid credentials.");
}
// Output: Login successful!OR (||) — At least one condition must be true
let isMember = false;
let hasCoupon = true;
if (isMember || hasCoupon) {
console.log("Discount applied!");
} else {
console.log("No discount available.");
}
// Output: Discount applied!Truthy and Falsy in Conditions
JavaScript evaluates non-boolean values as truthy or falsy inside conditions. Understanding this allows for shorter, cleaner code.
let username = "";
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please enter your username.");
}
// Output: Please enter your username.
// (empty string is falsy)Practical Example — ATM Simulation
let balance = 5000;
let withdrawAmount = 2000;
if (withdrawAmount <= 0) {
console.log("Enter a valid amount.");
} else if (withdrawAmount > balance) {
console.log("Insufficient balance.");
} else {
balance -= withdrawAmount;
console.log("Withdrawal successful!");
console.log("Remaining balance: " + balance);
}
// Output:
// Withdrawal successful!
// Remaining balance: 3000if vs switch — When to Use Which
| Situation | Best Choice |
|---|---|
| Comparing a range of values (e.g., marks between 0-100) | if...else if |
| Checking equality against many fixed values | switch |
| Simple true/false one-liner | ternary operator |
Key Points to Remember
- Use
ifto run code only when a condition is true - Use
elseto provide an alternative when the condition is false - Use
else ifto check multiple conditions in sequence - Use
switchwhen checking one variable against many fixed values - Always include
breakin switch cases to prevent fall-through - The ternary operator is a one-line shorthand for simple if/else expressions
- Logical operators
&&and||combine conditions in a single statement
