Making JavaScript Code More Readable and Robust: The Nullish Coalescing Operator
The null coalescing operator (??) is a binary operator introduced in ECMAScript 2020 (ES2020) that provides a concise way to handle null and undefined values. It evaluates to the first operand if it's not null or undefined, otherwise it returns the second operand.
How does it work?
- If the left operand (
operand1
) is not null or not undefined, the null coalescing operator returnsoperand1
itself. - If
operand1
is null or is undefined, the operator returns the right operand (operand2
).
Example:
let name = null;
let defaultName = "John Doe";
let greeting = name ?? defaultName; // greeting will be "John Doe"
name = "Alice";
greeting = name ?? defaultName; // greeting will now be "Alice"
Why use the null coalescing operator?
- Improved readability: It offers a more readable way to handle null and undefined values compared to traditional ternary operators or logical OR (||) operators.
- Safer code: It avoids potential errors that might occur when accessing properties of null or undefined objects.
Comparison with logical OR (||):
The null coalescing operator (??) is similar to the logical OR (||) operator, but with a key distinction:
||
returns the first truthy value, which includesnull
andundefined
.??
specifically checks fornull
andundefined
, and only returns the second operand in those cases.
let value1 = null;
let value2 = 0; // Falsy value, but not null or undefined
let result1 = value1 || value2; // result1 will be 0 (first truthy value)
let result2 = value1 ?? value2; // result2 will be null (because value1 is null)
Use the null coalescing operator when you want to provide a default value for a variable that might be null or undefined. It's particularly useful in:
- Assigning default values to variables during initialization.
- Accessing properties of objects that might be null or undefined to avoid potential errors.
- Conditional rendering in templating languages or frameworks.
// Without null coalescing operator:
let profileName = user.profile?.name; // Potential error if user.profile is null
if (profileName === undefined) {
profileName = "Guest";
}
// With null coalescing operator (more concise):
let profileName = user.profile?.name ?? "Guest";
// Even shorter for empty strings:
let userName = user.name ?? ""; // userName will be an empty string if user.name is null or undefined
Accessing Object Properties Safely:
// Without null coalescing operator:
let address = user.address?.street; // Potential error if user.address is null
if (address) {
console.log(address);
} else {
console.log("No address available");
}
// With null coalescing operator (cleaner and avoids potential errors):
let address = user.address?.street ?? "No address available";
console.log(address); // Prints "No address available" if user.address is null
Conditional Rendering (example with a templating engine):
<p>Welcome, {{ user.name ?? "Guest" }}!</p>
In this example, the templating engine will display "Welcome, Guest!" if user.name
is null or undefined.
Nullish Coalescing Assignment (new in ES2020):
This operator allows you to assign a default value in a single step:
let options = {};
options.fontSize ??= 16; // Sets options.fontSize to 16 if it doesn't exist
This is the most common alternative:
let name = null;
let defaultName = "John Doe";
let greeting = name || defaultName; // greeting will be "John Doe"
However, be cautious with this approach because ||
considers null
and undefined
as truthy values (anything that evaluates to false is falsy). So, if you have a falsy value (like 0
or an empty string ""
), it will be returned instead of the default value.
Ternary Operator:
This provides a conditional way to assign a value:
let name = null;
let defaultName = "John Doe";
let greeting = name === null ? defaultName : name; // greeting will be "John Doe"
While it works, the ternary operator can become less readable for complex expressions.
Optional Chaining (ES2020+):
Introduced alongside the null coalescing operator, optional chaining (?) allows safe access to properties of potentially null or undefined objects:
let user = null;
let userName = user?.name; // userName will be undefined
This is useful for nested object structures to avoid errors when accessing properties that might not exist. However, it doesn't provide a default value directly.
Choosing the Right Method:
- For simple default value assignment: Use the null coalescing operator (??) if your target environment supports ES2020 or later. It's concise and clear.
- If you need to handle other falsy values besides null and undefined: Stick with the logical OR (||) operator but be aware of its behavior.
- For complex conditional assignments: Consider the ternary operator, but remember its readability limitations.
- For safe property access and potential default values: Use optional chaining (?) in conjunction with either the null coalescing operator or another approach for assigning a default value.
javascript operators null-coalescing-operator