Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

if…else statements – JavaScript

Summary

if…else statement:

if (condition) {

} else {

}

Details

An if…else statement allows you to check if a condition is true or false. If it’s true, then the computer will execute a certain block of code. If it’s false, it will skip that section of code and run a different block of code (the else block).

If the condition is true

Here’s an example of an if…else statment where the condition is true:

if (1 > 0) {
  console.log("The condition is true");
} else {
  console.log("The condition is false");
}

In the example above, the statement “The condition is true” would print out to the console because 1 is greater than 0. It will skip the else statement.

If the condition is false

Here’s an example of an if…else statment where the condition is false:

if (1 < 0) {
  console.log("The condition is true");
} else {
  console.log("The condition is false");
}

In this example, the first block of code would be skipped and the statement “The condition is false” would print out to the console, since 1 is not less than 0.

Demo

Exercises

Try the following statements in the console:

if (1 > 0) {
  console.log('The condition is true');
} else {
  console.log('The condition is false');
}
if (1 < 0) {
  console.log('The condition is true');
} else {
  console.log('The condition is false');
}

The output from the first if statement will be “The condition is true”. The output from the second if statement will be “The condition is false”.

References

if…else statement on MDN

Back to: JavaScript Reference > JS Conditional Statements