DEV Community

Arijit Ray
Arijit Ray

Posted on

Decoding Javascript: The Nullish coalescing operator '??' is awesome!

A few days back, I was working on a project of mine where I wanted to set the value to a variable enabled based on a particular property of an object config. The interface for the object looks something like this:

interface IAuthConfig {
  enabledCookieAuth?: boolean;
  // other properties
}

function setDefault(config: IAuthConfig) {
  const enabled = config?.enabledCookieAuth
  //rest of the code
}

Enter fullscreen mode Exit fullscreen mode

For the variable enabled, I wanted to set the value of enabledCookieAuth of the config. Since enabledCookieAuth was an optional property, I wanted to set the default value of enabled true in case enabledCookieAuth was null or undefined.

ENTER Nullish coalescing ?? operator.

This particular operator is perfect for this requirement. The way it works is, it returns the first value that is defined. The code looks something like this:

const enabled = config?.enabledCookieAuth ?? true 
Enter fullscreen mode Exit fullscreen mode

The above code works exactly the same as:

const enabled = (config?.enabledCookieAuth !== null && config?.enabledCookieAuth !== undefined)? config?.enabledCookieAuth : true 
Enter fullscreen mode Exit fullscreen mode

Now the question that you might ask is, Why not use || OR operator?

Well, as I said earlier, ?? returns the first value that is defined whereas || returns the first value that is not falsy. || OR operator treats empty string (''), 0 or false as a falsy value. Meaning, even if config?.enabledCookieAuth is defined and set to false, config?.enabledCookieAuth || true will return true which doesn't serve our particular case.

const value1 = false
console.log(value1 ?? true)
// returns false as value1 is defined. 
console.log(value || true)
// returns true in all cases
Enter fullscreen mode Exit fullscreen mode

Although this operator has been there for quite sometime, it has been mostly unknown to the majority of the community.

Do note that it might not work with old browsers. Click here to check out its compatibility.

For further reference: Check out Nullish coalescing operator '??'

Top comments (0)