EcmaScript 6 offers powerful operators to streamline property access and conditional assignment in a concise and efficient manner.
In older JavaScript versions, the desired logic could be achieved using a try/catch block:
const query = succeed => (succeed ? { value: 4 } : undefined); let value = 3; for (let x of [true, false]) { try { value = query(x).value; } catch {} // Don´t assign if no .value } console.log(value); // Outputs: 4
Now, with optional chaining, this logic can be simplified considerably:
const query = succeed => (succeed ? { value: 4 } : undefined); let value = 3; for (let x of [true, false]) { value = query(x)?.value; // Assign only if `.value` exists } console.log(value); // Outputs: 4
The ?. operator checks if query(x) is non-null and undefined, and only then accesses the value property. If query(x) is null or undefined, it returns undefined without throwing an error.
For nullable values, the nullish coalescing operator (??) can be utilized:
const query = succeed => (succeed ? { value: 4 } : undefined); let value = 3; for (let x of [true, false]) { value ??= query(x).value; // Assign only if `value` is null or undefined } console.log(value); // Outputs: 4
The ?? operator compares the left-hand operand to null or undefined, and if true, assigns the right-hand operand. In this case, value will be updated only if it was initially null or undefined.
Note that these operators are supported in modern browsers and can be used with Babel for cross-browser compatibility.
The above is the detailed content of How Do Optional Chaining and Nullish Coalescing Simplify Null-Safe Property Access in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!