javascript-operador-coalescencia-nula

Nullish Coalescing Operator in JavaScript

  • 2 min

The nullish coalescing operator (??) is a logical operator that allows you to provide a default value when an expression is null or undefined.

This operator, introduced in ECMAScript 2020 (ES11), provides a more precise and clear way to handle null and undefined values (compared to other traditional approaches like using ||).

The nullish coalescing operator is very useful for simplifying and improving the readability of code when working with values that contain null or undefined.

Coalescence is a term that refers to the process of merging or fusing two or more elements into one.

Syntax of the Nullish Coalescing Operator

The syntax of the nullish coalescing operator is simple:

let result = value1 ?? value2;
Copied!

In this case,

  • If value1 is not null or undefined, result will take the value of value1.
  • If value1 is null or undefined, result will take the value of value2.

For example, in this case

let username = user.name ?? 'No idea, mate';

console.log(username); // 'No idea, mate'
Copied!

Here,

  • If the user’s name were Pedro, username would be Pedro.
  • Therefore, username takes the value ‘No idea, sir’.

Combination with Other Operators

The ?? operator fits wonderfully well (❤️) with other operators like the optional chaining operator ?..

let username = user?.name ?? 'Unknown';
console.log(username); // 'Unknown'
Copied!

In this case, username will be ‘No idea, sir’ both if,

  • user is null
  • user is not null, but its name property is null

In the previous example, without ?., if user had been null it would have thrown an exception.

Comparison with Other Methods