Nullish Coalescing - patrickcole/learning GitHub Wiki

Nullish Coalescing

Status

  • ECMAScript 2020 (ES11)

Syntax

"ifAvailable" ?? "useAsDefault"
// if the item on the left side of the ?? is available, use it
// otherwise, use the default value on the right side of the ??

Notes

  • provide a default value if a property is null or undefined
  • previously use of the OR-operator was used
  • however, the OR-operator treats falsy values (0, false, null, undefined) as reasons to use the default
  • developers might actually want to use false and only use a default if the value hasn't been declared

Example 1

  • this example will showcase the falsy problem:
let number = 0;
console.log(number || 87); // => 87
// the result is 87 above because 0 is falsy

// now using nullish coalescing, we can get
// the proper value of 0
console.log(number ?? 87 ); // => 0

Example 2

const role = API_RETURNED_ROLE ?? `user`;
console.log(role); // => 'user'

// since API_RETURNED_ROLE is undefined,
// the role of the user is just "user";

// later on the API_RETURNED_ROLE has been defined,
// now the code would look like this:

const API_RETURNED_ROLE = `admin`;
const role = API_RETURNED_ROLE ?? `user`;
console.log(role); // => 'admin'

// this could be after the user logged into the admin
// section of the application;

Sources