Home > Web Front-end > JS Tutorial > How Do Optional Chaining and Nullish Coalescing Improve Conditional Assignments in JavaScript?

How Do Optional Chaining and Nullish Coalescing Improve Conditional Assignments in JavaScript?

Susan Sarandon
Release: 2024-12-21 01:27:10
Original
890 people have browsed it

How Do Optional Chaining and Nullish Coalescing Improve Conditional Assignments in JavaScript?

Optional Chaining and Conditional Assignment in EcmaScript 6

In an effort to simplify conditional assignments and null-safe property access, EcmaScript 6 introduces several operators to enhance code efficiency and readability.

Optional Chaining (ECMAScript 2020)

Optional chaining, represented by the ?. operator, allows the safe traversal of nullable properties. In your example, you can simplify line 4 using optional chaining:

const query = succeed => (succeed ? { value: 4 } : undefined);

let value = 3;
for (let x of [true, false]) {
  value = query(x)?.value;
}
// Output: 4
Copy after login

Nullish Coalescing Assignment (ECMAScript 2021)

For conditional assignments, the nullish coalescing assignment operator ??= can be used. It assigns the value to the left-hand operand only if that operand evaluates to null or undefined. This avoids the need for try-catch blocks or explicit null checks:

query(x)?.value ??= value;
Copy after login

Considerations and Alternatives

  • Target Compatibility: Optional chaining and nullish coalescing assignment are supported in modern browsers and EcmaScript 2020 and 2021, respectively. Use "Can I Use" (https://caniuse.com/) to check compatibility for specific environments.
  • Babel Plugin: For older environments, a Babel plugin can be used to transpile these operators into compatible syntax.
  • CoffeeScript Alternative: The CoffeeScript idiom query(x).value if query(x)?.value? achieves similar behavior but involves repetition.
  • Object Property Access: In cases where you are setting an object property, the ??= operator ensures the assignment only occurs if the property is not already assigned. This avoids unnecessary setter calls.
  • Function Abstraction: Abstracting the logic into a function is not possible because conditional assignment cannot be expressed purely in function calls.

The above is the detailed content of How Do Optional Chaining and Nullish Coalescing Improve Conditional Assignments in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template