if else statements

When the boolean condition of an if statement evaluates to false, an else clause can be used to specify the behavior of the program. The following code will print "I am happy" to the console.

var weather = "warm";
if (weather === "cold") {
  console.log("so sad");
} else {
  console.log("I am happy");
}

If the boolean condition evaluates to true, then the code block associated with the if statement will be executed. If the boolean condition evaluates to false, the code block associated with the else statement will be executed instead.

In the following example, the boolean condition evaluates to true, so the code block associated with the if keyword is executed:

if ("a" === "a") {
  console.log("one direction <3");
} else {
  console.log("lfo");
}

The string "one direction <3" will be printed to the console. The code associated with the else keyword — console.log("lfo") — is not executed.

In this next example, the boolean condition evaluates false, so the code associated with the else clause is executed (and the code associated with the if clause is not executed):

var lovePoints = 100;
var heart = "closed";
if (heart === "open") {
  lovePoints = lovePoints + 1000;
} else {
  lovePoints = lovePoints - 60;
}
console.log(lovePoints);

The boolean condition evaluates to false, so the lovePoints variable is reassigned to lovePoints minus 60 (40). The number 40 is then printed to the console.

Question Click to View Answer

What does the following code print to the console?

if (5 === 6) {
  console.log("i get down in colombia");
} else {
  console.log("and look funny");
}

"and look funny"

The boolean condition (5 === 6) evaluates to false, so the code associated with the else keyword is executed.

What does the following code print to the console?

var me = "gringo";
if ("gringo" === me) {
  console.log("me llamo mateo");
} else {
  console.log("and my Spanish sucks");
}

me llamo mateo

The boolean condition ("gringo" === me) evaluates to true, so the code block associated with the if keyword is executed.

What does the following code print to the console?

var bestNumber = 8;
if (bestNumber / 2 / 2 === 2) {
  console.log("Dan Ostrov is awesome");
} else {
  console.log("I love math");
}

Dan Ostrov is awesome

The boolean condition (bestNumber / 2 / 2 === 2) evaluates to true, so the code associated with the if condition is executed.

<-- Previous (If Statements) Next (Introduction to Arrays) -->