DEV Community

Cover image for The difference between '||' and '??' in JavaScript.
Emmanuel (Emmo00)
Emmanuel (Emmo00)

Posted on

The difference between '||' and '??' in JavaScript.

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
ahmadadibzad profile image
Ahmad Adibzad

Thanks for sharing

Collapse
 
emmo00 profile image
Emmanuel (Emmo00)

I'm glad you like it

Collapse
 
anradev profile image
Rafael

Informative ! Thank you

Collapse
 
emmo00 profile image
Emmanuel (Emmo00)

I'm glad you like it. Thanks for reading