DEV Community

loading...
Cover image for Nullish Coalescing Operator

Nullish Coalescing Operator

bello profile image Bello ・Updated on ・2 min read


The nullish coalescing operator is the two question marks ??. It provides a default value.

Syntax:

result = a ?? b
Enter fullscreen mode Exit fullscreen mode

The syntax above means:

  • if a is defined, then a;
  • if a isn't defined, then b;

The syntax above can be rewritten as shown below:

result = (a !== null && a !== undefined) ? a : b;
Enter fullscreen mode Exit fullscreen mode

See the examples below:

if a is defined, then a;

const a = "breakfast"; // a is defined
const b = "lunch";

const result = a ?? b;
console.log(result); // breakfast
Enter fullscreen mode Exit fullscreen mode

if a isn't defined, then b;

let a; // a is undefined => const a = undefined;
const b = "lunch";

const result = a ?? b; 
console.log(result); // lunch
Enter fullscreen mode Exit fullscreen mode

If you are getting an error, the browser JavaScript engine does not understand the ?? operator.

SyntaxError: Unexpected token '?'
Enter fullscreen mode Exit fullscreen mode

In such a case, you need to upgrade the browser.



Nullish operator with other Operators

For a nullish operator used with other operators, it's advisable to use parentheses to specify the order of operations.

With parentheses () grouping:

let length, width;
const area = (length ?? 100) * (width ?? 50);

console.log(area) // 5000
Enter fullscreen mode Exit fullscreen mode

Without parentheses () grouping:

let length, width;
const area = length ?? 100 * width ?? 50;

console.log(area) // NaN
Enter fullscreen mode Exit fullscreen mode

Nullish operator with Logical Operators

const x = (5 && 10) ?? 15; // (5 && 10) = 10 => 10 ?? 15

console.log(x); // 10
Enter fullscreen mode Exit fullscreen mode

Nullish Operator Precedence
Nullish operator has the least precedence as compared to logical operators.

Operators Precedence
() 21
** 16
* 15
/ 15
% 15
+ 14
- 14
&& 7
OR 6
?? 5
? 4

Check out the full list of operators precedence at MDN.

The highest operator precedence is () in any math operation. It specifies the order of operations.

Happy Coding!!!


Buy me a Coffee


TechStack | Bluehost

  • Get a website with a free domain name for 1st year and a free SSL certificate.
  • 1-click WordPress install and 24/7 support.
  • Starting at $3.95/month.

Discussion (0)

pic
Editor guide