Skip to content

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

Another example

const person1 = {
  name: 'Alice',
  hobbies: ['reading', 'painting', 'swimming']
};

const person2 = {
  name: 'Bob'
};

// Accessing hobbies using optional chaining
const thirdHobbyPerson1 = person1.hobbies?.[2];
const fourthHobbyPerson1 = person1.hobbies?.[3];

const thirdHobbyPerson2 = person2.hobbies?.[2];
const fourthHobbyPerson2 = person2.hobbies?.[3];

// Logging the results
console.log('Third hobby (Person 1):', thirdHobbyPerson1); // Output: swimming
console.log('Fourth hobby (Person 1):', fourthHobbyPerson1); // Output: undefined

console.log('Third hobby (Person 2):', thirdHobbyPerson2); // Output: undefined
console.log('Fourth hobby (Person 2):', fourthHobbyPerson2); // Output: undefined

In this example, we have two person objects. person1 has a hobbies array with three elements, and person2 does not have a hobbies property. We use optional chaining (?.) to safely access elements within the hobbies array, even if the property doesn’t exist or the array is incomplete. This prevents errors from being thrown and allows the code to gracefully handle cases where the property is missing or undefined.

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

Leave a Reply

Your email address will not be published. Required fields are marked *