Combine Conditions With &&, || and !

In the last lesson, you gave club members a cheaper adult ticket with a nested if. The isMember check only ran once the outer chain had ruled out toddlers, children, and seniors. That works, but the rule itself fits in one sentence: members aged 16 to 64 get the member adult ticket.

In this lesson, you’ll learn to write that kind of sentence as a single condition. JavaScript has three logical operators that combine Boolean values into one answer. You’ll use && to check a range, || to accept alternatives, and ! to turn a condition around. You’ll predict each result before running it and finally flatten the nested ticket rule into one branch.

Check a Range With &&

The day trip includes a pottery workshop for visitors aged 5 to 15. To say “at least 5 and under 16” in code, you join two comparisons with the && operator, which you read as “and.” A condition built with && is true only when the conditions on both sides are true.

Create workshop.js in your course folder and type in this script:

Language: JavaScript Filename: workshop.js
const age = 12;

if (age >= 5 && age < 16) {
  console.log("You can join the pottery workshop.");
}

Each side of && is a complete comparison that names age. Run the script:

Language: Shell
$ node workshop.js
You can join the pottery workshop.

For 12, both comparisons are true, so the whole condition is true and the block runs.

A range has two ends, and both deserve a test. Open the Node REPL by running node, and predict each result before you press Enter:

Language: JavaScript
> let age = 4
undefined
> age >= 5 && age < 16
false
> age = 5
5
> age >= 5 && age < 16
true
> age = 15
15
> age >= 5 && age < 16
true
> age = 16
16
> age >= 5 && age < 16
false

At 4, the left side is false, and at 16, the right side is. After the first line, you change age without let, because the name already exists. Keep this REPL open, since you’ll come back to it.

Accept Several Values With ||

The bus to the lake runs on Saturdays and Sundays, and either day is enough. For that, you use the || operator, which you read as “or.” A condition built with || is true when at least one side is true and false only when both sides are false.

The REPL only runs JavaScript, not terminal commands, so open a second terminal with the plus (+) button in VS Code’s terminal panel. Create bus.js and type in this script:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.