Home > Web Front-end > JS Tutorial > How Do Optional Chaining and Nullish Coalescing Simplify Null-Safe Property Access in JavaScript?

How Do Optional Chaining and Nullish Coalescing Simplify Null-Safe Property Access in JavaScript?

Patricia Arquette
Release: 2024-12-09 11:39:11
Original
788 people have browsed it

How Do Optional Chaining and Nullish Coalescing Simplify Null-Safe Property Access in JavaScript?

NULL-Safe Property Access and Conditional Assignment in EcmaScript 6

EcmaScript 6 offers powerful operators to streamline property access and conditional assignment in a concise and efficient manner.

Conditional Assignment

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
Copy after login

Optional Chaining

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
Copy after login

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.

Nullish Coalescing

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
Copy after login

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!

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