ScanSkill

if…else

The if statement executes a statement if a specified condition is true.

Syntax

if (condition1)
  statement1
else if (condition2)
  statement2
else if (condition3)
  statement3
...
else
  statementN

Example

function positiveOrNegative(number) {
  let result;
  if (number > 0) {
    result = 'positive';
  } else if (number === 0) {
     result = 'zero';
  } else {
    result = 'negative';
  }
  return result;
}

console.log(positiveOrNegative(-5));
// Prints: negative

console.log(positiveOrNegative(0));
// Prints: zero

The if…else statement runs on the truth of the given condition, and when all condition fails it runs the else block. else if is used to latch on additional conditions to the if block.