Home >Web Front-end >JS Tutorial >How Do Optional Chaining and Nullish Coalescing Improve Null-Safe Property Access and Conditional Assignment in ES6 ?

How Do Optional Chaining and Nullish Coalescing Improve Null-Safe Property Access and Conditional Assignment in ES6 ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 01:22:16740browse

How Do Optional Chaining and Nullish Coalescing Improve Null-Safe Property Access and Conditional Assignment in ES6 ?

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:

  • Using nested if statements and try/catch blocks
  • Setting default values in advance
  • Functional approaches using lambda functions

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn