if...else

This YouTube video was created by Steve Griffith.

The if statement

The if statement is the most basic conditional statement in JavaScript. It executes a block of code only if a specified condition is truthy.

The if statement is made up of a condition and a statement. The condition is an expression that will be evaluated to be truthy or falsy. The condition is place between parentheses follow the if keyword. The statement is the block of codes, which will be executed if the condition is truthy

const number = 5

// Does number contain the value 5
if (number === 5) {
  // this block of code will execute
  console.log('Yes, number is equal to 5')
}

// Does number contain the value 6
if (number === 6) {
  // this block of code will not execute
  console.log('Yes, number is equal to 6')
}

The else statement

The second part of the if...else, is the else statement. This optional statement will execute its block of code only if the condition, from the previous if statement is falsy. While it is possible to have a if without an else, the reverse is not possible.

const number = 6

if (number === 5) {
  // this block of code will NOT execute
  console.log('Yes, number is equal to 5')
} else {
  // this block of code will execute
  console.log('No, number is NOT equal to 5')
}

The else if clause

When checking for multiple conditions, if...else statements can be nested to create an else if clause. Each condition will be checked only if the previous condition was falsy.

NOTE

There is no elseif keyword in JavaScript. The use of elseif in place of else if will result in a syntax error.

const number = 6

if (number === 5) {
  // this block of code will NOT execute
  console.log('Yes, number is equal to 5')
} else if (number === 6) {
  // this block of code will execute
  console.log('Yes, number is equal to 6')
}

Because an else if condition is only evaluated when the previous condition is falsy, using the else if clause can ensure that only one block of code is executed, which may not be possible when just using if statements.

Using if statements only

const number = 5

if (number <= 5) {
  // this block of code will execute
  console.log('Yes, number is less than or equal to 5')
}

if (number <= 10) {
  // this block of code will execute
  console.log('Yes, number is less than or equal to 10')
}

Using else if statements

const number = 5

if (number <= 5) {
  // this block of code will execute
  console.log('Yes, number is less than or equal to 5')
} else if (number <= 10) {
  // this block of code will NOT execute
  console.log('Yes, number is less than or equal to 10')
}