Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

2 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Introduction


Optional chaining is a new feature introduced in JavaScript (JS) since version ES2020. This feature simplifies accessing properties or methods of an object that may not exist or be empty.


Before optional chaining, when we wanted to access a property or method of an object, we usually had to check if the object existed or not. If it didn't exist, we had to use conditions to avoid errors. This led to writing long, hard-to-read, and complex code.


Optional chaining helps us solve this problem by allowing us to access properties or methods in a chain without having to check each step. If a step in the chain doesn't exist or is empty, optional chaining will return undefined instead of causing an error.


The syntax of Optional chaining is .?


Example


Here is an example illustrating how to use optional chaining in JS:

const user = {
  name: 'John',
  address: {
    city: 'New York',
    street: '123 Main Street'
  },
  hobbies: ['reading', 'painting']
};

// Truy cập thuộc tính name của đối tượng user
console.log(user?.name); // Output: 'John'

// Truy cập thuộc tính không tồn tại
console.log(user?.age); // Output: undefined

// Truy cập thuộc tính của đối tượng con
console.log(user?.address?.city); // Output: 'New York'

// Truy cập phương thức của đối tượng
console.log(user?.hobbies?.join(', ')); // Output: 'reading, painting'

// Truy cập phương thức không tồn tại
console.log(user?.getFullName?.()); // Output: undefined






As you can see in the example above, we use the ?. operator to access properties or methods of the user object. If a step in the chain doesn't exist, the result will be undefined.


Optional chaining helps us write shorter and more readable code. It also reduces the chance of errors when accessing properties or methods of an object.



Read more
On This Page