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 jacketThe 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
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.
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.