In JavaScript, we often come across situations where we need to check if a variable or property is null or undefined and provide a default value in case it is. Traditionally, we used the logical OR operator (||
) to achieve this. However, the Nullish Coalescing Operator (??
) provides a more concise and accurate way to handle this situation.
Introduction to the Nullish Coalescing Operator
The Nullish Coalescing Operator (??
) is a new addition to JavaScript introduced in the ECMAScript 2020 (ES11) specification. It serves as a shorthand operator to provide a default value if the left-hand side expression is either null or undefined.
Unlike the logical OR operator (||
), which considers falsy values such as 0
, ""
, NaN
, and false
, the Nullish Coalescing Operator only checks for null and undefined values. This makes it more suitable for scenarios where we want to distinguish between null/ undefined and other falsy values.
Usage Examples
Let’s look at some examples to better understand the usage of the Nullish Coalescing Operator:
- Using the Nullish Coalescing Operator with variables:
let name = null;
let defaultName = "John Doe";
let result = name ?? defaultName;
console.log(result); // Output: "John Doe"
In this example, the value of name
is null, so the Nullish Coalescing Operator assigns the defaultName
to the result
.
- Using the Nullish Coalescing Operator with properties:
const data = {
name: null,
age: 25
};
let result = data.name ?? "Unknown";
console.log(result); // Output: "Unknown"
Here, even though the name
property exists in the data
object, its value is null. The Nullish Coalescing Operator assigns the default value of “Unknown” to the result
.
- Using the Nullish Coalescing Operator with function arguments:
function greet(name) {
name = name ?? "Anonymous";
console.log(`Hello, ${name}!`);
}
greet(); // Output: "Hello, Anonymous!"
greet("John"); // Output: "Hello, John!"
In this example, if the name
parameter is null or undefined, the Nullish Coalescing Operator assigns the default value of “Anonymous” to the name
variable inside the greet
function.
Conclusion
The Nullish Coalescing Operator (??
) in JavaScript provides a concise and accurate way to handle default values for null or undefined variables or properties. By using this operator, you can simplify your code and make it more readable. It’s important to note that the operator is not supported in older versions of JavaScript, so make sure to check for compatibility before using it in your projects.