Introduction
You may have already met the ?? operator during your JavaScript coding sessions.
const result = first ?? second;
If you already wondered what it means, and why it is different from the || operator, you should learn a few interesting things in this post.
Context
In JavaScript, the logical operator || returns the first truthy value.
6 values only are considered as falsy values:
- false
- undefined
- null
- '' (empty string)
- NaN
- 0
Here are some examples of results obtained with || operator:
const nullValue = null; // falsy const emptyString = ''; // falsy const zero = 0; // falsy const randomNumber = 12; // truthy const randomString = 'hello'; // truthy nullValue || randomNumber // 12 nullValue || emptyString // '' emptyString || nullValue // null emptyString || randomNumber // 12 zero || randomNumber // 12 nullValue || randomNumber || randomString // 12
Difference with ??
?? pperator ("Nullish coalescing operator") returns the first value that is not null nor undefined.
If the value you want to get can be falsy (example: you may want to get a result equal to 0), you can use the ?? operator.
Here is a comparison of the results obtained with ??:
Conclusion
To sum up, in the expression x ?? y :
- if x is null or undefined, result will be y
- if x is different from null and different from undefined, result will be x.
The ?? operator is really useful when you only need to test the null or undefined value.