Mastering the else if
Statement in JavaScript
The else if
statement in JavaScript provides a way to test multiple conditions and execute code based on which condition is true. It allows you to handle more complex decision-making scenarios by sequentially evaluating conditions until one is met or all are skipped.
How the else if
Statement Works
The else if
statement is used in conjunction with if
. When the initial if
condition is false, JavaScript checks the else if
conditions in order. If none of the conditions are true, the else
block (if present) is executed.
Key Points to Remember
If the
if
condition is true, JavaScript will execute its block and skip allelse if
andelse
blocks.If the
if
condition is false, JavaScript evaluates each subsequentelse if
condition in order until it finds one that is true.If no conditions are true, the
else
block (if provided) will execute.
Syntax
javascriptCopyEditif (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the above conditions are true
}
Example 1: Checking Voting Eligibility
Let’s determine if a person is eligible to vote:
javascriptCopyEditlet age = 14;
if (age >= 18) {
console.log("You are eligible to vote.");
} else if (age < 18 && age > 10) {
console.log("You are not eligible to vote yet.");
} else if (age <= 10) {
console.log("You are too young to vote.");
}
Output when age = 19
:
cssCopyEditYou are eligible to vote.
Output when age = 14
:
cssCopyEditYou are not eligible to vote yet.
Example 2: Grading System
Determine a student’s grade based on marks:
Marks Range | Grade |
80 and above | A+ |
60 to 79 | A |
33 to 59 | B |
Below 33 | F |
Code
javascriptCopyEditlet marks = 75;
if (marks >= 80) {
console.log("A+");
} else if (marks >= 60) {
console.log("A");
} else if (marks >= 33) {
console.log("B");
} else {
console.log("F");
}
Output when marks = 89
:
cssCopyEditA+
Output when marks = 45
:
cssCopyEditB
Example 3: Seasonal Weather Checker
Let’s determine the season based on the month:
javascriptCopyEditlet month = "april";
if (month === "january" || month === "february") {
console.log("Winter is here.");
} else if (month === "april" || month === "may") {
console.log("Summer is here.");
} else if (month === "october" || month === "november") {
console.log("Autumn is here.");
} else {
console.log("Invalid month input.");
}
Output when month = "april"
:
csharpCopyEditSummer is here.
Enhancements to else if
Statements
Dynamic Inputs: Use the
prompt()
method in a browser to allow real-time user input for conditions.Switch Statements: For fixed values, a
switch
statement can be more concise and readable.Chaining Conditions: Combine conditions using logical operators (
&&
,||
) to reduce redundancy.