The difference between ‘||’ and ‘??’ in JavaScript.

Rmag Breaking News

Today, we are going to look at the behavior of two operators in JavaScript – the Logical OR Operator (||) and the Nullish Coalescing Operator (??). These operators are usually confused or misunderstood, so let’s get right to it.

They are usually used in writing one-liner “hotwires” (providing default values or fallbacks) and while they might seem similar, they serve different purposes and behave differently, especially in the context of handling null or undefined values in JavaScript.

Logical OR Operator ||

The logical OR operator || is a binary operator that returns the first truthy value it encounters or the last value if none are truthy.
JavaScript considers a value that is not among the following truthy:

false
0

” (empty string)
null
undefined
NaN

It is used to test whether at least one of the operands is truthy. if the left-hand operand is truthy, it is returned. If it is falsy, the right-hand operand is evaluated and returned.

Example

let name = Emmanuel;
let defaultName = Guest;
let displayName = name || defaultName; // Emmanuel

the name variable is not falsy, so the displayName is evaluated to “Emmanuel”. Now consider this:

let name = “”;
let defaultName = Guest;
let displayName = name || defaultName; // Guest

In this example, since name is an empty string (which is falsy), the || operator evaluates defaultName and assigns it to displayName.

Nullish Coalescing Operator (??)

The nullish coalescing operator (??) is also a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. Unlike the || operator, it does not consider other falsy values (false, 0, ”, NaN) as triggering the fallback.

Example

let age = 0;
let defaultAge = 18;
let userAge = age ?? defaultAge; // 0

In this example, even though age is 0 (which is considered falsy), the ?? operator does not consider it as a trigger for the fallback because 0 is not null or undefined. Therefore, userAge is assigned the value of age, which is 0.

In summary, the || operator is used to test whether at least one of the operands is truthy, while the ?? operator is used to provide a default value for a variable, but only considers null or undefined as falsy.

Leave a Reply

Your email address will not be published. Required fields are marked *