Else..If Statement

  • The else...if statement allows to look for more than two possible outcomes.

  • else...if always comes after the if statement and always before the else statement.

  • if / else...if / else

Example:

let stopLight = 'yellow';
 
if (stopLight === 'red') {
  console.log('Stop!');
} else if (stopLight === 'yellow') {
  console.log('Slow down.');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}

// Output: Slow down!

Example:

let season = 'summer';

if (season === 'spring') {
  console.log('It\'s spring! The trees are budding!');
} else if (season === 'winter') {
  console.log('It\'s winter! Everything is covered in snow.');
} else if (season === 'fall') {
  console.log('It\'s fall! Leaves are falling!');
} else if (season === 'summer') {
  console.log('It\'s sunny and warm because it\'s summer!');
}else {
  console.log('Invalid season.');
}

// Output: It's sunny and warm because it's summer!

Last updated