Language: EN

javascript-operador-coalescencia-nula

Nullish Coalescing Operator in JavaScript

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.

Coalescing 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;

In this case,

  • result will take the value of value1 if value1 is not null or undefined.
  • 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'

Here,

  • If the username were Pedro, username would be Pedro.
  • Therefore, username takes the value 'No idea, mate'.

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'

In this case, username will be No idea, mate whether,

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

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

Comparison with other methods of handling null values

Traditional conditionals

In earlier versions of JavaScript, handling null and undefined values was done using conditionals (||).

let name = value || 'User';

This is quite worse, as || considers any falsy value (like 0, false, '', etc) as a reason to use the default value.

So, it really does not just respond to undefined or null, but to a bunch of things!

Avoid using ||. It’s much more modern and “better” to use ??, that’s what it’s for 😉

Ternary Operator

The ternary operator is another alternative for handling null values. Although it is less elegant and can result in code that is harder to read:

let name = (value !== null && value !== undefined) ? value : 'User';

The ?? operator provides a more concise and clear way to handle null and undefined values.

Don’t do that, and use ?? for goodness’ sake! 😉