JavaScript If, Else If, Else and Switch
Learn how to control program execution using conditional statements in JavaScript. Understand if, if-else, else-if ladders, nested if, and switch statements with practical examples and outputs.
1. What Are Conditional Statements?
Conditional statements allow a program to make decisions based on whether a condition is true or false.
For example, a student result program can check marks and display whether the student has passed or failed. Similarly, an application can check a user's role before allowing a particular operation.
JavaScript provides the following conditional statements:
if— executes code when a condition is true.if-else— chooses between two alternatives.else if— checks multiple conditions in sequence.- Nested
if— places one condition inside another. switch— selects a case based on an expression's value.
2. The if Statement
The if statement executes a block of code only when
its condition evaluates to true.
Syntax
if (condition) {
// Code executes when the condition is true
}
Example: Check Passing Marks
let marks = 75;
if (marks >= 40) {
console.log("Student passed");
}
console.log("Program completed");
Output
Student passed
Program completed
Explanation:
The condition marks >= 40 is true because marks
are 75. Therefore, the message Student passed is
displayed. The program then continues to the next statement.
When the Condition Is False
let marks = 25;
if (marks >= 40) {
console.log("Student passed");
}
console.log("Program completed");
Output
Program completed
Since the condition is false, the message inside the
if block is skipped.
3. The if-else Statement
The if-else statement provides two alternatives.
If the condition is true, the if block executes.
Otherwise, the else block executes.
Syntax
if (condition) {
// Executes when true
} else {
// Executes when false
}
Example: Pass or Fail
let marks = 35;
if (marks >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}
Output
Fail
The marks are 35, which is below 40. Therefore, the condition
is false and the else block executes.
4. if-else Decision Flowchart
This simplified flowchart shows how JavaScript chooses a block according to the result of a condition.
Start
Check Condition
marks >= 40
TRUE
Display Pass
FALSE
Display Fail
End
5. The else-if Ladder
An else if ladder is used when multiple conditions
must be checked in sequence. JavaScript evaluates conditions from
top to bottom and executes the first matching block.
Syntax
if (condition1) {
// First condition
} else if (condition2) {
// Second condition
} else if (condition3) {
// Third condition
} else {
// No previous condition matched
}
Example: Student Grades
Assume the following grading rules for this example:
| Marks | Grade |
|---|---|
| 90 and above | A |
| 75 to 89 | B |
| 60 to 74 | C |
| 40 to 59 | D |
| Below 40 | Fail |
let marks = 82;
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("Fail");
}
Output
Grade B
Explanation:
The marks are 82. The first condition is false, but
marks >= 75 is true. JavaScript displays
Grade B and skips the remaining branches.
marks >= 40 is placed first, higher grades may
never be reached.
6. Nested if Statements
A nested if statement is an if statement
placed inside another conditional block. It is useful when a second
condition should be checked only after the first condition succeeds.
Example: Course Admission
let marks = 75;
let documentsSubmitted = true;
if (marks >= 60) {
if (documentsSubmitted) {
console.log("Admission eligible");
} else {
console.log("Submit your documents");
}
} else {
console.log("Minimum marks requirement not met");
}
Output
Admission eligible
The marks requirement is satisfied, so JavaScript checks the
second condition. Since the documents are also submitted,
the program displays Admission eligible.
7. The switch Statement
The switch statement selects a case based on the
value of an expression. It can be useful when comparing one
expression against several possible values.
Syntax
switch (expression) {
case value1:
// Statements
break;
case value2:
// Statements
break;
default:
// No matching case
}
Example: Day Selection
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");
}
Output
Wednesday
Explanation:
The value of day is 3, so the matching
case 3 executes. The break statement
exits the switch block after displaying the message.
default block executes when no case
matches. Without a break, execution can continue
into subsequent cases.
8. Conditional Statements Decision Diagram
Choose the conditional statement based on the number of alternatives and the type of decision your program needs to make.
Need to Make a Decision?
One Condition
Use if
Two Alternatives
Use if-else
Multiple Conditions
Use else if
Multiple Exact Values
Consider switch
9. Practical Program: Simple Calculator
Let us create a simple calculator that performs an operation
based on a selected operator. This example uses a
switch statement.
Step 1: Create a File
Create a file named calculator.js.
Step 2: Write the Program
let a = 20;
let b = 5;
let operator = "*";
switch (operator) {
case "+":
console.log("Result:", a + b);
break;
case "-":
console.log("Result:", a - b);
break;
case "*":
console.log("Result:", a * b);
break;
case "/":
if (b !== 0) {
console.log("Result:", a / b);
} else {
console.log("Cannot divide by zero");
}
break;
default:
console.log("Invalid operator");
}
Step 3: Run the Program
node calculator.js
Step 4: Expected Output
Result: 100
Explanation:
The variable operator contains "*",
so the multiplication case executes. The result is
20 * 5 = 100.
10. Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
Using = instead of a comparison |
= assigns a value rather than checking equality. |
Use an appropriate comparison operator. |
| Incorrect condition order | A broad condition can match before a more specific one. | Place conditions in the intended order. |
| Missing braces | Only the next statement belongs to an unbraced conditional. | Use braces to make blocks clear. |
Missing break in switch |
Execution may continue into later cases. | Add break when fall-through is not intended. |
| Ignoring the default case | Unexpected values may not be handled. | Use default when a fallback is appropriate. |
11. Practice Task
Student Grade Calculator
Create a JavaScript program that:
- Stores marks in a variable.
- Uses
ifto check whether marks are valid. - Uses an
else ifladder to assign a grade. - Displays Pass or Fail using a conditional statement.
- Uses a
switchstatement to display a message based on the grade. - Displays an appropriate message for invalid input.
Important Points
ifexecutes a block when its condition is truthy.if-elseselects between two alternatives.else ifchecks multiple conditions in order.- Nested
ifstatements check conditions inside other conditional blocks. switchselects cases based on an expression's value.breakprevents unintended fall-through in switch cases.- Use
defaultto handle unmatched switch values when needed.
Summary
JavaScript conditional statements control program flow based on conditions. The if statement handles a single condition, if-else selects between alternatives, else-if checks multiple conditions, and nested if statements allow dependent checks. The switch statement is useful for selecting among multiple exact values. These statements help developers build decision-based programs such as grade calculators, admission checks, and calculators.