DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Nullish Coalescing Operator ??

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay