Yes, altough your array may not be null, you don’t know if an item with the index 0 exists. However, the ? operator only accesses the property foo if the expression before evaluates something that is not null or undefined.
Example
var x = [];
console.log(x[0]?.foo); // undefined
console.log(x[0].foo); // error
x = [{foo: 1}];
console.log(x[0]?.foo); // 1
console.log(x[0].foo); // 1
Keep in mind that accessing an array at an index without knowing if that index exists is risky and should not be done unless really needed.
Also, try testing before asking simple questions like these.
3
Answers
Yes, altough your array may not be null, you don’t know if an item with the index
0
exists. However, the?
operator only accesses the propertyfoo
if the expression before evaluates something that is notnull
orundefined
.Example
Keep in mind that accessing an array at an index without knowing if that index exists is risky and should not be done unless really needed.
Also, try testing before asking simple questions like these.
Yes, you can use this.
I feel you should at the very least try and do this in an online js-sandbox tool before asking these simple questions.
It is possible to use the optional chaining operator with an array, you just need to add a dot before calling the index