Introduction to Else If Statements in JavaScript

Posted by

An “else if” statement in JavaScript allows you to add additional conditions to an if/else statement. The basic syntax is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if condition1 and condition2 are both false
}

[/dm_code_snippet]

You can add as many “else if” statements as needed. The conditions are evaluated in the order they are written and the first one that evaluates to true will execute its corresponding code block. If none of the conditions evaluate to true, the code in the “else” block will be executed.

Here’s an example that checks the value of a variable called “age” and assigns a string to another variable called “status” based on that value:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

if (age < 18) {
  status = "minor";
} else if (age >= 18 && age < 65) {
  status = "adult";
} else {
  status = "senior";
}

[/dm_code_snippet]

This code will check if age is less than 18, then check if the age is greater than or equal to 18 and less than 65, if both of these conditions are not met, it will be a senior.

It is worth noting that you can use if else statement alone, but adding else if statement allows you to check for multiple conditions.