Line At A Time
Lesson 11: Else If
Else If Check several conditions, one after another.
1const number = 2;
2if (number === 1) {
3 console.log("one");
4} else if (number === 2) {
5 console.log("two");
6} else {
7 console.log("something else");
8}
Terminal
$ node main.js
two
Every line, explained
const number = 2;
const creates a variable: a named box that stores a value. const is short for "constant": once a value is stored, that name can never be given a new value. Modern JavaScript uses const for most things. The semicolon ; marks the end of the statement.
if (number === 1) {
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. 2 === 1 is false, so this block is skipped.
console.log("one");
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: number is not 1.
} else if (number === 2) {
} else if (...) { adds another check that is only tried when the one above was false. JavaScript tests each condition top to bottom and runs the first block whose condition is true. 2 === 2 is true, so this block runs.
console.log("two");
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 line runs.
} 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. Only runs when every check above it failed.
console.log("something else");
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 else if above already matched.
}
This } closes the else block.