Home >Web Front-end >JS Tutorial >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
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;
Considerations and Alternatives
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!