The ES2020 was just approved by the TC39 committee, and in the proposal, Nullish Coalescing is a thing. What is "Optional chaining"?
Well, it's another way to assign fallback values other than using the OR operators we might normally use.
This video goes over an example to hopefully make more sense of it. 🤓
In this example, we will provide default values but keep values other than null or undefined. If you want more information, scroll down. 👇
The Nullish Coalescing Operator returns the results of the right-hand-side expression if the left-hand-side expression is either null or undefined.
If that sounds confusing, don't worry it's actually really simple.
There is often use cases where falsy values could be a wanted default like the number zero or an empty string. Using the Nullish Coalescing Operator makes it easy to check only for null
and undefined
before falling through the OR evaluation. I think the example below will make it a little less complicated sounding.
Using the nullish coalescing operator versus OR operator.
### Using the OR Operator.
// example based on MDN docs.
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue || "default for A";
const valB = emptyText || "default for B";
const valC = someNumber || 0;
console.log(valA); // "default for A"
console.log(valB); // "default for B" (as the empty string is falsy)
console.log(valC); // 42
Using the Nullish Coalescing Operator
// example from MDN
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
So as you can see, nothing too crazy. Just another tool to add to your JavaScript belt.
Subscribe on Codú Community