Understanding the Optional Chaining Operator
The concept of the optional chaining operator is to streamline expressions by halting execution when encountering a null
or undefined
value.
Imagine wanting to ensure that a user object is not null or undefined in your code:
public static getUserName(user: IUser): string {
if (user?.firstName && user?.firstName !== ""){
return user.firstName;
}
if (user?.lastName && user?.lastName !== ""){
return user.lastName;
}
return user?.username || "";
}
Furthermore, this operator can be applied to arrays and functions as well:
// Retrieve the first element of an array only if it exists
const element = array?.[0];
// Call a function if it is defined
myFunction.(args);
In cases where concise coding is preferred, consider utilizing the nullish coalescing operator for improved readability and efficiency.
Exploring the Nullish Coalescing Operator
The nullish coalescing operator serves a similar purpose as the logical operator ||
, but distinguishes itself by only falling back to default values when encountering null
or undefined
. This mitigates issues related to using ||
with non-nullish values such as 0
or Nan
.
Here's how you can refactor the previous code snippet:
public static getUserName(user: IUser){
return user?.firstName ?? user?.lastName ?? user?.username ?? "";
}
By employing both operators within your codebase, you enhance robustness significantly.
Unveiling Pitfalls of the Logical Operator ||
Consider a scenario where users set timers within an application. If a user inputs a time greater than 0, their input should be retained; otherwise, a default time applies. Here's a common implementation:
const time = userTime || defaultTime;
When handling input validation, keep in mind that the logical operator ||
treats 0
as a nullish expression, leading to unexpected results. To address this, switch to the nullish coalescing operator:
const time = userTime ?? defaultTime;
With this adjustment, the code operates as intended under various user inputs.