Skip main navigation

Logical operators

In this activity, we will explore logical operators like *and*, *or*, and *not*.
A computer screen with code on it.
© Packt

Whenever you want to check two conditions in one, or you need to negate a condition, the logical operators come in handy. You can use and, or, and not.

And

The first one we will have a look at is and. If you want to check whether x is greater than y and y is greater than z, you would need to be able to combine two expressions. This can be done with the && operator.

It will only return true if both expressions are true:

 let x = 1; 
let y = 2;
let z = 3;

With these variables in mind, we are going to have a look at the logical operators:

 console.log(x < y && y < z);

This will log true, you can read it like this: if x is smaller than y and y is smaller than z, it will log true. That is the case, so it will log true.

The next example will log false:

 console.log(x > y && y < z); 

Since x is not greater than y, one part of the expression is not true, and therefore it will result in false.

Or

If you want to get true if either one of the expressions is true, you use or. The operator for this is ||.

These pipes are used to see if either one of these two is true, in which case the whole expression evaluates to true.

Let’s have a look at the or operator in action:

 console.log(x > y || y < z); 

This will result in true, whereas it was false with &&. This is because only one of the two sides needs to be true in order for the whole expression to evaluate to true. This is the case because y is smaller than z.

When both sides are false, it will log false, which is the case in the next example:

 console.log(x > y || y > z);

Not

In some cases you will have to negate a Boolean. This will make it the opposite value.

It can be done with the exclamation mark, which reads as not:

 let x = false; 
console.log(!x);

This will log true, since it will simply flip the value of the Boolean. You can also negate an expression that evaluates to a Boolean, but you would have to make sure that the expression gets evaluated first by grouping it.

 let x = 1; 
let y = 2;
console.log(!(x < y));

x is smaller than y, so the expression evaluates to true. But, it gets negated due to the exclamation mark and prints false to the console.

© Packt
This article is from the free online

Introduction to JavaScript

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now