Languages
[Edit]
EN

TypeScript - ?? operator (Nullish Coalescing)

9 points
Created by:
evangeline
420

In this short article we would like to explain what is Nullish Coalescing Operator (??) in TypeScript, and how it works.

?? was  introduced in TypeScript 3.7 to help in getting alternative value (we can call it default value too) when current variable value is null or undefined.

Note: ?? is new feature of ECMAScript (now we have Dec 2020).

Practical example:

So, it is equivalent of:

Warning

Edit

Do not use interchangeably:

because:

  • || returns defaultValue always when !!inputValue operation returns true,
  • ?? returns defaultValue always only when inputValue === null || inputValue === undefined operation returns true.

Examp[le list of !!inputValue operation cases was presented below:

Practical example for || operator:

Practical example for ?? operator:

References

Edit
  1. Nullish Coalescing - TypeScript Docs
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join