DEV Community

loading...

Nullish Coalescing Operator ??

jabermudez11 profile image Justin Bermudez ・1 min read

Have you ever seen the double question mark operator in javascript??

It can be used like this

const firstName = null;
const lastName = null;
const nickname = null;

console.log(firstName ?? lastName ?? nickname ?? "anonymous")
// => "anonymous"
Enter fullscreen mode Exit fullscreen mode

The console did not log null from the first 3 variables, but the last one. This is because the Nullish Coalescing Operator will output the first defined value. The 3 variables we defined are set null so they are all faulty and have no value.

This looks like it is similar to another operator we have that looks like this "||". The OR operator almost does the same thing but the first TRUTHY value. As opposed to the Nullish Coalescing Operator returns the first DEFINED value.

Review our list of Falsy Values:

  1. false
  2. 0
  3. -0
  4. 0n
  5. ""
  6. null
  7. undefined
  8. NaN

When looking at a ?? b if a is defined with a value, then we will get "a", otherwise we will return b.

const a = 0;
const b = 1;
console.log(a ?? b)
// => 0
Enter fullscreen mode Exit fullscreen mode

The value of a is returned here since we defined a with the value 0. If this was using the OR operator

const a = 0;
const b = 1;
console.log(a || b)
// => 1
Enter fullscreen mode Exit fullscreen mode

a is defined with a faulsy value so we will get retrned the value of b.

Discussion (0)

pic
Editor guide