Nullish coalescing operator (??)

Nullish coalescing operator (??)

ยท

2 min read

Table of contents

No heading

No headings in the article.

Have you encountered a scenario during comparison where if first operand is null or undefined, and you want to use the right operand which has defined value? Many Javascript developers faced this scenario often ๐Ÿ™ƒ. Hence, ES11 introduced a logical operator called nullish coalescing operator (??) which assigns right operand to result of expression if left operand is null or undefined.

let leftoperand = null;
let rightoperand = "ES11"
let result = leftoperand ?? rightoperand
// result = ES11
let result = undefined ?? "JS is cool"
// result = JS is cool

You may ask me, even logical OR(||) gives the same result. What is the difference then?

let result = undefined || "JS is cool"
// result = JS is cool

The difference is between how logical OR(||) and null coalescing operator treat falsy values. What are falsy values by the way? In Javascript, false, 0, " "(empty string), undefined, null, NaN are falsy values. Whenever comparison between falsy values and truthy values(other than falsy value. Simple isn't it!), always truthy value is assigned after evaluation whenever logical OR(||) is used. For example

let result = false || true
// result = true

But if we compare falsy values other than null and undefined with truthy values, falsy value(other than null and undefined) is evaluated and returned.

let result = false ?? true
// result = false

Lets look at more examples

let result = NaN || 130;
// result = 130

let finalAnswer = NaN ?? 130;
// finalAnswer = NaN (?? operator ignores ONLY undefined and null and assigns right operand to result)

let counter = 0 ?? 160
// counter = 0

let maxAge = null ?? 100
// maxAge = 100

There is one more point about ?? operator. It can not be used with logical operators.

let result = 3 > 5 || 20 ?? 45 //SyntaxError: unexpected token '??'

To use ?? with logical operator, parentheses() can be made use of.

let result = (3 > 5 || 20) ?? 45 //Works
// result = 20

Summary

  • Null coalescing logical operator introduced in ES11.
  • Helps in avoiding null and undefined values getting inside the code. Hence helps in debugging.
  • ?? not allowed to use with logical operators unless specified with parentheses () to increase the precedence of ??

Thank you for reading this. Please provide feedbacks if any.

Until next time, See you :).

ย