Optional chaining syntax in JavaScript?.

?. is Optional Chaining in JavaScript, which is a new feature introduced by ES11 (also known as ES2020). Optional chaining syntax provides a concise way to access properties of nested objects while avoiding errors caused by a property not existing.

The main advantage of optional chaining is that you don't get errors when accessing nested object properties, but instead return undefined when the property doesn't exist. This is useful when working with deeply nested object structures to avoid having to use multiple conditional statements to check for the existence of each property.

Here's an example using optional chaining:

const person = {
    
    
  name: "Alice",
  address: {
    
    
    city: "New York",
    zipCode: "12345"
  }
};

console.log(person.address?.city); // 输出 "New York"
console.log(person.address?.street?.name); // 输出 undefined,而不会抛出错误

In this example, the person object has a nested address object, and the address object does not have a nested street property. By using optional chaining syntax, we can avoid errors when trying to access the street property.

It is important to note that optional chaining syntax applies not only to property access, but also to function calls. For example:

const obj = {
    
    
  foo: {
    
    
    bar: function() {
    
    
      return "Hello, world!";
    }
  }
};

console.log(obj.foo?.bar?.()); // 输出 "Hello, world!"
console.log(obj.baz?.()); // 输出 undefined,而不会抛出错误

In summary, optional chaining syntax is a new feature that helps simplify and improve the robustness of your code, especially when dealing with complex object structures.

Guess you like

Origin blog.csdn.net/weixin_43160662/article/details/132352987
Recommended