JavaScript Code


JavaScript If-Else


If-Else Statement

In JavaScript, if-else statement is used to execute one of the two blocks based on a condition.

Syntax

if (condition) {
  //code
} else {
  //code
}

where

  • if is keyword.
  • condition is a boolean expression.
  • else is keyword.
  • code is any valid JavaScript code.

If condition is true, then if-block code is run. If condition is false, then else-block code is run.

Examples

1. In the following program, we use an if-else statement to check if a is even or not.

a = 10;

if (a%2 == 0) {
  console.log("a is even.");
} else {
  console.log("a is not even.");
}

2. In the following program, we use an if-else statement to check if supplies are good, or more supplies are needed.

supplies = 10;

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