🟨 JavaScript Q29 / 121

What is nullish coalescing?

AI-Powered Answer ✓ Answered

Nullish coalescing is a JavaScript operator (??) introduced in ECMAScript 2020 that provides a way to define a default value for variables that are 'nullish' (i.e., `null` or `undefined`). It offers a more precise alternative to the logical OR (||) operator when dealing with default values.

What is the Nullish Coalescing Operator (??)?

The nullish coalescing operator (??) returns its right-hand operand when its left-hand operand is null or undefined. Otherwise, it returns its left-hand operand. This makes it ideal for providing default values when you only want to fall back if the value is explicitly missing or unassigned, rather than just falsy.

Consider the following syntax: leftOperand ?? rightOperand. If leftOperand is null or undefined, the expression evaluates to rightOperand. Otherwise, it evaluates to leftOperand.

Key Differences from Logical OR (||)

The main distinction between ?? and || lies in what they consider 'falsy'. The || operator returns its right-hand operand if its left-hand operand is any falsy value (e.g., false, 0, '' (empty string), null, undefined). In contrast, ?? only treats null and undefined as 'nullish'.

javascript
const undefinedValue = undefined;
const nullValue = null;
const zeroValue = 0;
const emptyString = '';
const falseValue = false;

console.log(undefinedValue ?? 'default'); // Output: 'default'
console.log(nullValue ?? 'default');      // Output: 'default'
console.log(zeroValue ?? 'default');      // Output: 0
console.log(emptyString ?? 'default');    // Output: ''
console.log(falseValue ?? 'default');     // Output: false

console.log(undefinedValue || 'default'); // Output: 'default'
console.log(nullValue || 'default');      // Output: 'default'
console.log(zeroValue || 'default');      // Output: 'default'
console.log(emptyString || 'default');    // Output: 'default'
console.log(falseValue || 'default');     // Output: 'default'

When to Use Nullish Coalescing

You should use the nullish coalescing operator when you specifically want to provide a default value only if a variable is null or undefined, and you want to treat other falsy values (like 0, false, or '') as valid and desirable outcomes.

  • Setting default configuration options where 0 or false are valid settings.
  • Providing fallback values for optional parameters in functions.
  • Safely accessing nested properties where a property might be null or undefined, but not necessarily an empty string or zero.
javascript
function processConfig(config) {
  const logLevel = config.logLevel ?? 1; // Default to 1 if logLevel is null/undefined
  const enableCache = config.enableCache ?? true; // Default to true if enableCache is null/undefined
  const timeout = config.timeout ?? 5000; // Default to 5000ms if timeout is null/undefined

  console.log(`Log Level: ${logLevel}`);
  console.log(`Cache Enabled: ${enableCache}`);
  console.log(`Timeout: ${timeout}ms`);
}

processConfig({ logLevel: 0, enableCache: false });
// Output:
// Log Level: 0
// Cache Enabled: false
// Timeout: 5000ms

processConfig({});
// Output:
// Log Level: 1
// Cache Enabled: true
// Timeout: 5000ms

In summary, nullish coalescing provides a powerful and precise tool for handling default values in JavaScript, making your code more robust and intentions clearer when distinguishing between 'missing' and 'falsy but valid' values.