In JavaScript, the logical OR operator (||) and the nullish coalescing operator (??) are two distinct operators that serve different purposes when it comes to handling values. Understanding the differences between these operators is crucial for writing robust and error-free JavaScript code. In this article, we will delve into the nuances of || and ?? operators, providing detailed examples to illustrate their behaviors and use cases.

The Logical OR Operator (||)

The logical OR operator (||) in JavaScript is commonly used for providing a default value when dealing with falsy values such as null, undefined, 0, false, and empty strings.

Example: (*Javascript)

// Using the logical OR operator to provide a default value
const defaultValue = someValue || 'default';

In the above example, if someValue is falsy, the expression will evaluate to ‘default’. However, if someValue is truthy, the expression will evaluate to someValue.

JavaScript considers a value that is not among the following truthy:

  • false
  • 0
  • '' (empty string)
  • null
  • undefined
  • NaN
let name = "";
let defaultName = "Chloe";
let displayName = name || defaultName; // Chloe

The Nullish Coalescing Operator (??)

The nullish coalescing operator (??) was introduced in ECMAScript 2020 as a more specific alternative to the logical OR operator. It specifically checks for null or undefined values and provides a default value only if the operand on the left-hand side is null or undefined.

Example: (*Javascript)

// Using the nullish coalescing operator to provide a default value
const defaultValue = someValue ?? 'default';

In this example, if someValue is null or undefined, the expression will evaluate to ‘default’. If someValue is any other falsy value, the expression will evaluate to someValue.

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.

Key Differences and Use Cases

  1. Treatment of Falsy Values:
  • The logical OR operator ( || ) considers all falsy values (such as 0, false, and empty strings) as candidates for providing a default value.
  • The nullish coalescing operator ( ?? ) only considers null and undefined as candidates for providing a default value.



2. Use Cases:

  • The logical OR operator ( || ) is commonly used for providing a default value in a broader sense, including cases where 0, false, or empty strings should trigger the default value.
  • The nullish coalescing operator ( ?? ) is specifically designed for scenarios where null or undefined should trigger the default value, while other falsy values should not.


By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

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