Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

The else Branch

An if statement runs its block only when the condition is true. Often you also want to do something when it's false. That's what else (otherwise) is for:

const temperature = 12;
if (temperature > 25) {
    console.log("Take a cap");
} else {
    console.log("Take a jacket");
}

This prints:

Take a jacket

The condition temperature > 25 is false, so the program skips the first block and runs the block after else. The two blocks are called branches: like a path that splits in two, the program always takes exactly one of them. If the condition is true, it takes the first branch; otherwise, the second. It never runs both, and it never skips both.

else has no condition of its own: it takes every case the if didn't. It can't stand on its own, either. It always comes right after the closing } of an if block. A semicolon between them, }; else {, splits them apart, and the program ends with an error: SyntaxError: Unexpected token 'else'.

We write } else { on one line. You may also see else on a new line under the }; JavaScript accepts both.

Instructions

  1. 1

    The monitor now costs 5000, so the program prints nothing. Add an else branch to the if statement that prints I will not buy the monitor.

  2. 2

    Change monitorPrice to 3500 and run the program again. Now the condition is true, so the program takes the first branch and prints only I will buy the monitor.

Back

2/13

  1. 1. The if Statement
  2. 2. The else Branch
  3. 3. Comparison Operators
  4. 4. Assign or Compare?
  5. 5. Quiz: Assign or Compare?
  6. 6. Boolean Values
  7. 7. More Options: else if
  8. 8. Logical Operators: And
  9. 9. Logical Operators: Or
  10. 10. Quiz: Logical Operators
  11. 11. Negation
  12. 12. Nested Conditions
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.