Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
4 Strings
5 Arrays
6 Objects
8 Functions
When dealing with only two blocks, the first one executes if the condition is true, and if it is false, we can run the else block. However, when we encounter situations where multiple blocks need to be executed based on certain conditions, we employ additional constructs like else if
to handle such scenarios effectively.
Here is how we add the else if
statement:
if (condition1) { // Code to execute if the condition is true } else if (condition2) { // Code executes if condition1 is false and condition2 is true. } else { // Code to execute if condition1 and condition2 are false }
We can add as many else if
statements as we need.
let score = 75; if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else if (score >= 70) { console.log("Grade: C"); } else if (score >= 60) { console.log("Grade: D"); } else { console.log("Grade: F"); }
The above code prints a message based on the condition:
These statements provide a structured way to handle different scenarios based on varying conditions.