Understanding the JavaScript Null Coalescing Operator (??)
The null merge operator (??) is a JavaScript feature introduced in ECMAScript 2020. Using this operator, you can handle default values of variables which may be null or undefined.
Before its introduction, the logical operator OR (||) was commonly used for this purpose, but it was not always suitable because it handles all false values. THE ?? The operator offers a more precise and clearer alternative.
In this article, you will learn the concept of the null merge operator, its benefits, how to use it, and some examples.
Let’s get straight to it!🚀
What is the null coalescence operator (??)?
The null merge operator (??) is a logical operator used to check if a value is null or undefined.
If its left operand is null or undefined, then it returns its right operand (fallback value).
If its left operand is not null or undefined, then it returns the left operand.
For example:
let userInput = null;
let inputValue = userInput ?? 'default';
console.log(inputValue); // Output: default
In this example, userInput is null, so the ?? The operator returns the “default” fallback value.
Now you may be wondering how is this different from logical OR || operator?🤔
This is different from logical OR || operator, because the || The operator returns the right operand if the left operand is a false value (like false, 0, ”, NaN, etc.), not just null or undefined. While the ?? The operator only focuses on null or undefined.
Why use the Nullish Coalescing operator (??) instead of the Logical OR operator (||)?
THE ?? The operator only focuses on null and undefined values, while the || The operator checks for any false values (like false, 0, ”, NaN, etc.), which can lead to unexpected results.
For example:
let obj = {};
let value = obj.age ?? 'default value';
console.log(value); // Output: default value
In this example, the age is not defined in the object, so the ?? The operator returns the “default value” fallback value.
Now, let’s take another example to understand this better.
let userInput = '';
let inputValue = userInput ?? 'default';
console.log(inputValue); // Output: <empty string>
In this example, userInput is an empty string, which is a false value and not null or undefined, so the ?? The operator returns
Now let’s see what happens if you use || instead of ??.
let userInput = '';
let inputValue = userInput || 'default';
console.log(inputValue); // Output: default
Here the || The operator returns the default value because it checks for any false values.
Another reason to use ?? instead of || The operator is readability.
Code using ?? is generally clearer and more readable because its purpose is directly related to handling nulls and undefineds. It provides a fallback value when a variable is null or undefined, making the code more readable and less error-prone.
Null operator?? with logical operators AND/OR
You can also use the ?? operator with other logical operators to check multiple conditions.
For example:
let userInput = null;
let inputValue = userInput ?? 'default' || 'alternative';
console.log(inputValue); // Output: default
In this example, inputValue gets the “default” value because the left operand (userInput) is null.
Now let’s see what happens if userInput is not null.
let userInput = '';
let inputValue = userInput ?? 'default' || 'alternative';
console.log(inputValue);
Oops !! This generates an error😬😬
But why does this happen?🤔
This happens because the null merge operator (??) cannot be used directly in logical operators such as || OR and && AND without appropriate parentheses around it.
The reason is that JavaScript has specific rules for operator precedence, which refer to the priority levels of different operators, i.e. the order in which operations are evaluated.
For example: ?? has a priority lower than || and &&, so placing it in parentheses ensures that it is evaluated first in logical expressions.
So the correct way to use ?? directly with logical operators:
let userInput = '';
let inputValue = (userInput ?? 'default') || 'alternative';
console.log(inputValue); // Output: alternative
Here the parentheses force JavaScript to evaluate the ?? operation first, then the result is used in the logical OR operation with “alternative”.
Conclusion
In JavaScript, the null merge operator (??) provides a clearer and more consistent way to handle default values for null and undefined. This avoids the pitfalls of || operator by not returning unintended false values. Using the Nullish Coalescing Operator (??) can make your code cleaner, more readable, and less error-prone, especially when dealing with optional values. Understanding and using Nullish Coalescing Operator (??) can lead to more efficient and maintainable code.
That’s all for today.
I hope this was helpful.
Thanks for reading.
Here are 45 more JavaScript tips and tricks for developers.
For more content like this, click here.
Follow me on X(Twitter) for daily web development tips.
Keep coding!!
Stackademic 🎓
Thank you for reading to the end. Before leaving:
- Please consider applaud And following the writer! 👏
- Follow us X | LinkedIn | YouTube | Discord | Newsletter | Podcast
- Create a free AI-powered blog on Differ.
- More content on Stackademic.com
- Do you have a story to share? Join our global community of writers today!
Understanding the JavaScript Null Merge Operator (??) was originally published in Stackademic on Medium, where people are continuing the conversation by highlighting and responding to this story.