Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

3 Conditional Structures

5 If Else If Else

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:

  • If the score is 90 or above, the grade is "A".
  • If the score is between 80 and 89, the grade is "B".
  • If the score is between 70 and 79, the grade is "C".
  • If the score is between 60 and 69, the grade is "D".
  • Otherwise, the grade is "F".

These statements provide a structured way to handle different scenarios based on varying conditions.