Optional chaining array in JavaScript | Example code

  • by

JavaScript Optional chaining array work as a short-circuit and returns undefined if accessing the array results was null or undefined, your code won’t break.

user?.friends?.[0]

Using just the ? alone makes the compiler think you’re trying to use the conditional operator.

Note: Optional chaining is only used for reading not for assignments.

Optional chaining array

Simple example code used with bracket notation like above, but it can also be used with dot notation property access.

<!DOCTYPE html>
<html>
<body>

  <script>
    const user = {
      name: 'JOhn',
      age: 25,
      settings: {
        theme: {
          mode: 'dark',
          text: '#d7e0ff',
          background: '#f87070',
          font: 'Kumbh Sans, sans-serif'
        },
      },
      friends: ['Tim', 'Steve', 'Mike'],
    }

    // use optional chaining 
    const first = user?.friends?.[0]
    console.log(first) 

    console.log(user?.friends)

  </script>

</body>
</html> 

Output:

Optional chaining array in JavaScript

Do comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.