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
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!