NULL-safe Property Access and Conditional Assignment in EcmaScript 6
The ability to access properties of objects that may be null or undefined without causing errors is referred to as null-safe property access. Conditional assignment, on the other hand, allows for values to be assigned only if specific conditions are met.
In EcmaScript 6 , several operators support both null-safe property access and conditional assignment.
Optional Chaining (?.)
Introduced in ES2020, optional chaining allows accessing properties of objects that may be null or undefined without exceptions. It uses the ?. operator, which returns undefined instead of raising an error:
const query = succeed => (succeed ? { value: 4 } : undefined); let value = 3; for (let x of [true, false]) { value = query(x)?.value; } console.log(value); // Output: 4
Nullish Coalescing Assignment (??=)
The nullish coalescing assignment operator (??=) assigns a value to a variable only if the current value is null or undefined. It returns the result of the assignment:
let value = 3; value ??= query(false)?.value; console.log(value); // Output: 3
Compatibility
Optional chaining is supported in major modern browsers and Node.js versions, while nullish coalescing assignment is supported in browsers and Node.js v14 . For older environments, consider using Babel or a polyfill.
Alternatives
Before these operators, workarounds included:
Conclusion
Optional chaining and nullish coalescing assignment provide powerful tools for concise null-safe property access and conditional assignment in EcmaScript 6 . They simplify code, enhance readability, and reduce the potential for errors.
The above is the detailed content of How Do Optional Chaining and Nullish Coalescing Improve Null-Safe Property Access and Conditional Assignment in ES6 ?. For more information, please follow other related articles on the PHP Chinese website!