Well, even though we figured out the correct syntax, the code doesn't make much sense to me.
The optional chaining in the code above is making sure, that the result of myArray.filter(x => x.testKey === myTestKey)
is not null
and not undefined
(you can have a look at the TS output). But it is not possible anyway, because the result of the filter
method is always an array
. Since JavaScript doesn't throw "Array bounds exceeded", you are always safe when you try to access any index - you will get undefined
if this element doesn't exist.
More example to make it clear:
const myArray: string[] = undefined
console.log(myArray.filter(x => x)?.[0]) //throws Cannot read property 'filter' of undefined
//in this example the optional chaining protects us from undefined array
const myArray: string[] = undefined
console.log(myArray?.filter(x => x)[0]) //outputs "undefined"
?
does a null check to prevent long use of&&
&&
chains.myArr?.[0]