Line At A Time
Lesson 8: If Statements
If Statements Only run code when a condition is true.
1const age = 10;
2if (age > 8) {
3 console.log("You are older than 8");
4}
Terminal
$ node main.js
You are older than 8
Every line, explained
const age = 10;
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 (age > 8) {
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. Here > means "greater than", and 10 > 8 is true, so the code inside runs.
console.log("You are older than 8");
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 } closes the if block.