The Nullish Coalescing Operator In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the The Nullish Coalescing Operator In JavaScript.
The Nullish Coalescing Operator In JavaScript
The nullish coalescing operator (??) is a new operator introduced in JavaScript (ECMAScript 2020) that allows you to assign a default value to a variable if it is null or undefined.
The nullish coalescing operator works similar to the logical OR operator (||) but it only returns the second operand if the first operand is null or undefined.
Code For Nullish Coalescing operator
let x;
let y = x ?? "default value";
console.log(y);
Output
“default value”
If the first operand is any other falsy value, such as 0, an empty string, or false, the nullish coalescing operator will return that value instead of the default.
let x = 0;
let y = x ?? "default value";
console.log(y);
Output
0
The nullish coalescing operator is particularly useful when working with optional values that could be null or undefined, and you want to provide a default value for them.
let user = { name: "John", age: 25 };
let name = user.name ?? "anonymous";
console.log(name);
Output
“John”
It can also be useful when working with function calls that may return null or undefined.
let data = getData() ?? "default data";
Conclusion
It is important to note that the nullish coalescing operator is different from the logical OR operator because it only returns the default value when the first operand is null or undefined, whereas the logical OR operator returns the default value when the first operand is any falsy value.
The nullish coalescing operator is a more recent addition to javascript and works only in the latest versions of javascript.