Line At A Time
Lesson 13: The AND Operator
The AND Operator Combine conditions with &&.
1const hungry = true;
2const haveSnacks = false;
3if (hungry && haveSnacks) {
4 console.log("Snack time!");
5} else {
6 console.log("No snacks right now");
7}
Terminal
$ node main.js
No snacks right now
Every line, explained
const hungry = true;
A boolean is a value that can only be true or false (both lowercase in JavaScript).
const haveSnacks = false;
A boolean is a value that can only be true or false (both lowercase in JavaScript).
if (hungry && haveSnacks) {
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. && means AND: the condition is only true if BOTH sides are true. true && false is false, so this block is skipped.
console.log("Snack time!");
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: we have no snacks.
} 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("No snacks right now");
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.