
Understanding the Nullish Coalescing (??) Operator in JavaScript

I'll admit: I am possibly a little late to the game when it comes to the Nullish coalescing operator (??). I have only come across a real‑world use in a code review earlier this week, which then resulted in a long and interesting conversation about the difference between ?? and the logical OR operator: ||.
So: in modern JavaScript development, the introduction of the nullish coalescing operator (??) brought with it a convenient way to handle default values in a concise and expressive manner. The operator provides a more precise and reliable alternative to the logical OR (||) operator in certain scenarios. In this article, I hope to explore the nullish coalescing operator, understand its behaviour, and compare it with the logical OR operator that we all know and love.
Understanding the Nullish Coalescing Operator
The nullish coalescing operator (??) is designed to evaluate and return the right‑hand side (RHS) expression only if the left‑hand side (LHS) expression is nullish, which includes null and undefined. It allows us to provide a default value when dealing with potentially nullish values without relying on falsy values like empty strings, zero, or false.
Basic Usage
So, let's start with a fairly basic example to demonstrate the behaviour of the nullish coalescing operator:
const name = null;console.log(name ?? 'Anonymous'); //=> 'Anonymous'Here, the variable name is set to null. When we use the nullish coalescing operator, it checks if name is nullish and ‑ because it is explicitly set to null in this example ‑ returns RHS expression ('Anonymous').
Comparison with Logical or Operator:
To better understand the differences between ?? and ||, let's compare the nullish coalescing operator with the logical OR operator in a more real‑world type of scenario:
const foo = { name: '', age: 0,};// Using nullish coalescing operatorconsole.log(foo.name ?? 'Anonymous'); //=> ''console.log(foo.age ?? 25); //=> 0// Using logical OR operatorconsole.log(foo.name || 'Anonymous'); //=> 'Anonymous'console.log(foo.age || 25); //=> 25Here, we have an object foo with properties name and age. The nullish coalescing operator considers both an empty string ('') and zero (0) as non‑nullish values, resulting in the default values being ignored and the LHS being returned.
When we use the logical OR operator instead, it evaluates foo.name and foo.age as falsy values, (both an empty string ('') and zero (0) are falsy, but not nullish). As a result, the RHS values 'Anonymous' and 25 are returned.
More Advanced Examples
As you might expect, the nullish coalescing operator can be combined with other JavaScript features, such as function calls and object properties. To delve into more advanced examples, let me share a couple of examples that illustrate its practical use.
Example 1: Function Parameter Defaults
const greetUser = name => { name = name ?? 'Anonymous'; console.log(`Hello, ${name}!`);};greetUser(); //=> Hello, Anonymous!greetUser('John'); //=> Hello, John!In this example, the greetUser function takes a name parameter. By using the nullish coalescing operator, we can assign a default value of 'Anonymous' to name if it is null or undefined. In this way, we can ensure that the function can still execute correctly even if the name argument is omitted.
Example 2: Object Property Access
const user = { name: 'John', preferences: { theme: 'dark', language: null, },};const theme = user.preferences.theme ?? 'light';const language = user.preferences.language ?? 'en';console.log(theme); //=> 'dark'console.log(language); //=> 'en'Here, we have an object user with a preferences property that contains nested properties theme and language. By using the nullish coalescing operator, we can safely access these properties whilst providing default values if they are null or undefined. This prevents unexpected errors when attempting to access properties that may be missing or have nullish values.
The Wrap‑Up
To offer a bit of a conclusion: the nullish coalescing operator (??) provides a concise and accurate way to handle default values in JavaScript, particularly when dealing with potentially nullish values.
The big difference between ?? (the nullish coalescing operator) and || (the logical OR operator) is that ?? considers only nullish values (null and undefined), whilst treating other falsy values as valid. The logical OR operator considers all falsy values.
Understanding the nuances and differences between these operators allows us as developers to choose the appropriate approach based on the specific requirements in real‑world development.
Categories:
Related Articles

Understanding setTimeout() in JavaScript. Understanding

Differences Between Falsy and Nullish Values in JavaScript. Differences Between Falsy and Nullish Values in JavaScript

Solving the 'Jump Game' Problem with Greedy Algorithms. Solving the 'Jump Game' Problem with Greedy Algorithms

Best Practices for Angular Routing and Lazy Loading. Best Practices for Angular Routing and Lazy Loading

JavaScript String Manipulation: substring() vs. substr(). JavaScript String Manipulation:
substring()vs.substr()
LeetCode: Solving the 'Merge Two Sorted Lists' Problem. LeetCode: Solving the 'Merge Two Sorted Lists' Problem

Type Coercion in JavaScript: Implicit vs. Explicit Conversion. Type Coercion in JavaScript: Implicit vs. Explicit Conversion

Disabling Gatsby Telemetry. Disabling Gatsby Telemetry

Array.find(), Array.some(), and Array.every() in JavaScript. Array.find(),Array.some(), andArray.every()in JavaScript
Throttling vs. Debouncing in JavaScript: Managing Event Frequency. Throttling vs. Debouncing in JavaScript: Managing Event Frequency

CSS box‑sizing: Controlling the Element Box Model. CSS
box‑sizing: Controlling the Element Box ModelReferenceError: Window is Not Defined in Gatsby. ReferenceError: Window is Not Defined in Gatsby