Coding for All
Lesson 9: Else
Else Do one thing when true, another when false.
1const isRaining = false;
2if (isRaining) {
3 console.log("Take an umbrella!");
4} else {
5 console.log("Enjoy the sunshine!");
6}
Terminal
$ node main.js
Enjoy the sunshine!
Every line, explained
const isRaining = false;
A boolean is a value that can only be true or false (both lowercase in JavaScript).
if (isRaining) {
if checks the condition inside its round brackets. If the condition is true, JavaScript runs the code between { and }; if it is false, it skips that code completely. The condition is just the variable isRaining, which is false, so this block is skipped.
console.log("Take an umbrella!");
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Skipped: the condition above is false.
} else {
} else { attaches an "otherwise" branch. When the if condition is false, the code inside the else block runs instead. Exactly one of the two blocks runs, never both.
console.log("Enjoy the sunshine!");
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. This is the line that runs.
}
This } closes the else block.