if statements

Conditional statements — commonly called if statements — evaluate a boolean condition, then execute code only if the condition is true. The following if statement will print "5 equals 5" to the console.

if (5 === 5) {
  console.log("5 equals 5");
} // prints "5 equals 5" to the console

The code block console.log("5 equals 5") is executed because the boolean condition, 5 === 5, returns true:

console.log(5 === 5); // true

When the boolean condition is false, the code in the if code block is not executed:

if ("blah" === "hi") {
  console.log("this is not printed to the console");
} // (nothing is printed to the console)

The string "blah" is not equal to the string "hi", so the boolean condition "blah" === "hi" evaluates to false. The code in the if code block is not executed.

When constructing if statements, remember to put the boolean condition in parentheses () and the code block in brackets {}: javascript if ("test" === "test") { console.log("The code block to be executed goes in brackets.") }

Question Click to View Answer

What does the following code print to the console?

console.log("A B C");
var singer = "michael";
if (singer === "michael") {
  console.log("It's easy as 1 2 3");
}
console.log("It's simple as do re me");
A B C
It's easy as 1 2 3
It's simple as do re mi

The variable singer is assigned to the value "michael". The string "michael" is the same as the other string "michael" so the code block associated with the if statement is executed.

What does the following code print to the console?

console.log("I like");
if (32 > 55) {
  console.log("evil clowns and");
}
console.log("funny jokes");
I like
funny jokes

The conditional 32 > 55 evaluates to false, so the string "evil clowns and" is not printed to the console.

What does the following code print to the console?

var y = "cypress hill";
if (7 === 7) {
  y = "house of pain";
}
console.log(y);

"house of pain"

The boolean condition 7 === 7 evaluates to true, so the code block associated with the if statement is executed and the y variable is reassigned to the string "house of pain".

What does the following code print to the console?

var number = 5;
if (number > 10) {
  number = number + 4;
}
console.log(number);

5

The variable number is assigned to the value 5. The boolean condition (number > 10) evaluates to false, so the code block associated with the if statement is not executed and the number variable is not reassigned. The number variable is still assigned to 5 when it is printed to the console.

<-- Previous (Introduction to Types) Next (If Else Statements) -->