NULL-safe Property Access & Conditional Assignment in EcmaScript 6
In JavaScript, it can be cumbersome to access properties of objects that may be null or undefined. Additionally, conditionally assigning values to variables can involve error-prone try/catch blocks.
The optional chaining (?.) operator, introduced in ES2020, provides a concise way to access properties of nullable objects. It returns undefined if the property does not exist, eliminating the need for explicit checks.
For conditional assignment, the nullish coalescing assignment operator (??=) assigns a value to a variable only if it is currently null or undefined. This avoids overwriting existing values unnecessarily.
Example:
const query = (succeed) => (succeed ? { value: 4 } : undefined); let value = 3; for (let x of [true, false]) { value = query(x)?.value ?? value; } console.log(value); // Output: 4
In this example, the assignment only occurs if query(x).value exists, otherwise the old value is retained. The optional chaining ensures that no error is thrown when accessing the property if query(x) is undefined.
Other Notes:
The above is the detailed content of How Can Optional Chaining and Nullish Coalescing Improve Null-Safe Property Access and Conditional Assignment in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!