Since I started developing in React, I have noticed how most online snippets and tutorials avoid the optional chaining operator, as well as the nullish coalescing operator. Although they are fairly recent innovations, they are already over a year old.
So, I think the reason behind this is that there is a lack of education about what they are, how to start using them, how, why, and when. Let's try to address all of these points.
What They Are
Let's see both the optional chaining operator and the nullish coalescing operator definition according to MDN Web Docs.
Optional Chaining
The optional chaining operator (
?.
) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.The
?.
operator is like the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
. When used with function calls, it returnsundefined
if the given function does not exist. — MDN Web Docs
Nullish Coalescing
The nullish coalescing operator (
??
) is a logical operator that returns its right-hand side operand when its left-hand side operand isnull
orundefined
, and otherwise returns its left-hand side operand. — MDN Web Docs
How To Enable Them
Both operators were officially released with the ECMA-262 11th Edition JavaScript language specification. Since these are quite fresh features, only certain versions of React support them.
In order to use them, the following requirements must be met:
Plus, TypeScript developers need TypeScript ≥ 3.7.
How To Use Them
Let's see the syntax required to use both operators.
Optional Chaining
obj.val?.prop // default use
obj.val?.[expr] // optional chaining with expressions
obj.arr?.[index] // array item access with optional chaining
obj.func?.(args) // optional chaining with function calls
Nullish Coalescing
leftExpr ?? rightExpr // default use
Why and When To Use Them
Let's see why these two operators were introduced to JavaScript and when you should use them to take advantage of their power.
Optional Chaining
When developing in JavaScript, you often need to access deeply-nested properties from tree-like structures. The common solution is to write a long chain of property accesses. The problem is that if any of the intermediate references in the chain is null
or undefined
, JavaScript will throw a _TypeError: Cannot read property ‘name' of undefined_
error.
So, you may end up writing custom logic to avoid this from happening. Not only is this code ugly, but it also makes your codebase less readable. This is why the optional chaining operator was introduced.
Before optional chaining, you had to write something like this:
if (obj && object.property1 && object.property1.property2) {
object.property1.property2.toLowerCase()
}
With optional chaining, you can achieve the same result with a single, cleaner, and more readable line of code:
obj.property1?.property2.toLowerCase()
This was just a simple example, but you can find a more in-depth guide here.
Plus, keep in mind that the optional chaining operator works only for declared variables. If there was no obj
variable, then a ReferenceError
error would be thrown.
Also, you should use ?.
only with optional properties and variables. This means that if according to your coding logic the obj
variable must exist, but the property1
property is optional, you should write obj.property1?.property2
.
Nullish Coalescing
When you need a variable to have a default value, you may think of using the OR operator (||
), as follows:
let value;
let defaultValue = value || 'Hello World!';
This may turn into an error very difficult to spot. In fact, ||
is a boolean logical operator. So, the left-hand-side operand is automatically converted to a boolean during evaluation time. This means that in case the left-hand-side operand is any JavaScript falsy value (0
, ''
, NaN
, null
, undefined
), the default value will not be returned.
The nullish coalescing operator was introduced to overcome this issue. In fact, it avoids this pitfall by only returning the second operand when the first one evaluates to either null
or undefined
(but no other falsy values):
const nullValue = null;
const emptyText = ""; // falsy
const aNumber = 42;
const val1 = nullValue ?? "Default Value 1";
const val2 = emptyText ?? "Default Value 2";
const val3 = aNumber ?? 0;
console.log(val1); // "Default Value 1"
console.log(val2); // "" (as the empty string is not null or undefined)
console.log(val3); // 42
This was just a simple example, but you can find a more in-depth guide here.
Conclusion
Today we looked at what the optional chaining and nullish coalescing operators are, how to use them, why, and where. Although they were introduced in JavaScript over a year ago, many developers still have not tried them. This is because they are still quite a novelty and education is necessary to understand everything required to start adopting them, and this what was this article was aimed at.
Thanks for reading! I hope that you found this article helpful.
The post "Start Using Optional Chaining and Nullish Coalescing in React" appeared first on Writech.
Top comments (0)