JavaScript Logical Operators

JavaScript Logical Operators

·

6 min read

In JavaScript, there are logical operators that will help us concisely express complex conditions. Let's say we wanted to travel to an island by boat or by plane. In English, we use or in the previous sentence to express we're willing to take either mode of transportation.

In JavaScript, we can use " || "

const boat = true;
const plane = false;

const willTravel = boat || plane;
console.log(willTravel);//true

In the example above, one of the conditions is true in the OR operation (the boat), therefore the value stored in willTravel is true!

The || operator is commonly refferred to as the Logical OR because it will evaluate to true if either (or both) of the inputs are true

Additionally, we'll see an AND operator requiring both conditions to be true. As well, we'll see a NOT operator for negating a condition.

We will also see how these logical operators behave with non-boolean values and how we can use that to our advantage.

Excited? Let's get coding!

Logical OR

There are cases in code where we want to say "this condition" or "this other condition". If either of the conditions is true, let's do something!

It would be quite ugly to write this with if statements every time:

if(car){
    driveToAirport();
}
else if(motorcycle){
    driveToAirport();
}
else if(truck){
    driveToAirport();
}

If we needed to change the driveToAirport function, we would have to change it in 3 places

It's goog practice to DRY up your code. This stands for "Don't Repeat Yourself". You should always try to avoid code redundancy where possible!

Let's try to accomplish the same functionality with the Logical OR (||) operator:

if(car || motorcycle || truck ){
    driveToAirport();
}

Phew, much cleaner! The || operator takes two values and returns true if either boolean value is true:

console.log(true || false);//true
console.log(false || true);//true
console.log(true || true);//true
console.log(false || false);//false

Default Operator

In the last stage, we referred to || as the Logical OR operator.

This operator is also sometimes referred to as the default operator, due to its behaviour with truthy and falsy values.

Truthy and Falsey

In JavaScript, there are two boolean values: true and false.

There are also a spectrum of values that are considered "truth-y" and "false-y"

Values that are considered "truth-y" will behave like true when used with logical operators.

Let's consider the OR ( || ) operator with booleans:

console.log(true || false);//true
console.log(false || true);//true

Because at least one of these boolean values are true, the result is true.

This works the same with truthy values!

console.log(3 || false);//3
console.log(false || "something" || false);//something

The value 3 and "something" are behaving like true in these two statements! These two values are considered truthy.

What other values are truthy?

To answer that, let's look at the falsey values. It is much easier to enumerate all the falsey values. The truthy values will be all the values in JavaScript that are not falsey.

Falsey values include false, 0 , "", null, undefined, and NaN. These values behave like false when encontering logical operators:

console.log(0 || true);//true
console.log("" || true);//true

Take, for example:

console.log("" || "Something Else");//Something Else

The empty string "" is a falsey value, so || will take the second value in this operation

This can be pretty useful with variables! We can use this to create a default message if one is not defined:

const message = WELCOME_MESSAGE || "Hello there!";

Here the message is guaranteed a truth value if WELCOME_MESSAGE is empty.

And it's not just limited to empty strings either:

const age = user.age || 99;

If user.age is undefined or 0 we will default to 99. For that matter user.age could be any falsey value and it would default to 99

Can you think of any other good examples for default values?

AND Operator

Another important logical operator is &&, which is called Logical AND:

console.log(true && true);//ture
console.log(true && false);//false
console.log(false && true);//false
console.log(false && false);//false

Notice that both values must be true for the expression to evaluate to true. We need this to be true AND that to be true as well.

We can, of course, do the same thing with variables:

let a = true;
let b = true;
console.log(a&&b);//true
b = false;
console.log(a&&b);//false
console.log(b&&a);//false

Guard Operator

We learned that || can be referred to as the Logical OR operator or the default operator.

Similarily, the && operator can be referred to as the Logiacl AND operator or the guard operator!

We can use the operator to guard against run-time exceptions (or errors) when dealing with falsey values.

Let's see some examples

const user = { name: 'bob'}
console.log(user && user.name);//bob
const user2 = undefined;
console.log(user2 && user2.name);//undefined

Notice how in the first example we successfully retrieve the user's name, while the second example returns undefined.

In the second example, if we tried to retrieve this property directly, we would hit a run-time exception:

const user2 = undefined;
console.log(user2.name);
//Uncaught TypeError: Cannot read property 'name' of undefined

Trying to log user2.name right here would result in an uncaught error.

Uncaught errors are bad! They'll stop our code execution. This could result in some really ugly errors for users.

NOT Operator

The final logical operator we will discuss is the ! operator. Commonly referred to as the NOT or negation operator.

This operator will flip true and false :

console.log(!true);//false
console.log(!false);//true

It will also flip truthy and falsey values:

console.log(!2);//false
console.log(!undefined);//true

If you apply the negation operator to a truthy or falsey value twice, you'll wind up with the corresponding boolean value. Since 2 is a truthy value !!2 will evaluate to true

The order of logical operators is very important, as it determines how expressions are evaluated and ultimately affects the result of the operation.

In JavaScript, the logical operators are evaluated from left to right and have different levels of precedence. The three logical operators are:

  1. AND (&&)

  2. OR (||)

  3. NOT (!)

The order of precedence for these operators is:

  1. NOT (!)

  2. AND (&&)

  3. OR (||)

This means that NOT has the highest precedence, followed by AND, and then OR. When multiple operators are used in an expression, the one with the highest precedence is evaluated first.

For example, consider the following expression:

let result = true || false && true;

Because AND has higher precedence than OR, the expression is evaluated as:

let result = true || (false && true);

Which results in the result being assigned true

To avoid ambiguity and ensure that expressions are evaluated as intended, it is important to use parentheses to group logical operations as necessary.