3

JavaScript Optional Chaining with Array Index

 1 year ago
source link: https://masteringjs.io/tutorials/fundamentals/optional-chaining-array
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript Optional Chaining with Array Index

Feb 15, 2023

JavaScript optional chaining works with array indexes. Just add the ?. before your square brackets []. Looks weird, but it works!

const characters = [
  { name: 'Jean-Luc Picard', age: 59 },
  { name: 'Will Riker', age: 29 }
];

// `?.[2]` is how you access the 2nd element with optional chaining
characters?.[2]?.age; // undefined
characters?.[1].age; // 29

characters[1]?.doesnt?.exist; // undefined

You can't use ?. with a number, that causes a syntax error. But you can also use ?.[] with variables as follows.

const index = 1;

characters?.[index].age; // 29

More Fundamentals Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK