Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is if...else if... statement in JavaScript?
The if...else if... statement allows JavaScript to evaluate multiple conditions sequentially and execute the first matching condition's code block.
Syntax
The syntax of an if...else if statement is as follows:
if (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 no condition is true
}
How It Works
JavaScript evaluates conditions from top to bottom. When it finds the first true condition, it executes that block and skips the rest. If no condition is true, the else block runs (if present).
Example: Book Classification
<html>
<body>
<script>
var book = "maths";
if (book == "history") {
document.write("<b>History Book</b>");
} else if (book == "maths") {
document.write("<b>Maths Book</b>");
} else if (book == "economics") {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
</script>
</body>
</html>
<b>Maths Book</b>
Example: Grade Calculator
<html>
<body>
<script>
var score = 85;
var grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
document.write("Score: " + score + "<br>Grade: " + grade);
</script>
</body>
</html>
Score: 85 Grade: B
Key Points
- Only the first matching condition executes
- Remaining conditions are skipped once a match is found
- The
elseblock is optional but recommended for handling unexpected cases - Use
else ifinstead of nestedifstatements for better readability
Conclusion
The if...else if... statement provides an efficient way to handle multiple conditions in JavaScript. It evaluates conditions sequentially and executes only the first matching block, making your code more organized and readable.
Advertisements
