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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 12:51:13422browse

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

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 ??= operator cannot be used directly for conditional property assignment, as it would always assign the value regardless of the property's existence.
  • Optional chaining can be used for nested property access, e.g., a?.b?.c, where a, b, and c are properties of nullable objects.
  • Babel-preset-env can be used to transpile JavaScript code with optional chaining and nullish coalescing operators for compatibility with older environments.

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!

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