If...Else Statements

If we wanted to add some default behavior to the if statement, we can add an else statement to run the block of code when the condition evaluates to false.

Example:

if (false) {
	console.log('The code in this block will not run.');
} else {
	console.log('But the code in this block will run.');
}

// Output: But the code in this block will run.

In the above example:

  • else keyword is used following the if statement.

  • Has a code block that is wrapped around the curly braces {}.

  • The code inside the else statement will execute when the if statement evaluates to false.

NOTE if..else statement allows us to automate the yes-or-no questions, also known as binary decisions.

Example:

let sale = true;

sale = false;

if(sale) {
  console.log('Time to buy!');
} else {
  console.log('Time to wait for a sale.');
}

// Output: Time to wait for a sale.

Last updated