JavaScript Code

JavaScript If-Else-If

If-Else-If Statement

if (condition1) {
} else if (condition2) {
} else if (condition3) {
} else {
  • if, else are keywords
  • condition1, condition2, condition3,… are boolean expressions
  • code is any valid JavaScript code

Any number of else if blocks are allowed.

else block is optional.

if condition1 is true, then if-block code is run. if condition1 is false, and condition2 is true, then first else-if-block code is run. if condition2 is also false, and condition3 is true, then second else-if-block code is run. if no condition is true, then else-block code is run.


1. if-else-if statement to check if value in a is positive, negative, or zero.

a = 10;

if (a > 0) {
  console.log("a is positive.");
} else if (a < 0) {
  console.log("a is negative.");
} else {
  console.log("a is zero.");

2. if-else-if statement to check if value in supplies is good(>5), need more supplies(>=0), or if supplies are in deficit(<0).

supplies = 10;

if (supplies > 5) {
  console.log("Supplies are good.");
} else if (supplies >=0) {
  console.log("Need more supplies.");
} else {
  console.log("Deficit in supplies.");