My Unexpected Undefined

I got myself with a TypeError
yesterday for trying to read the properties of undefined while using find to return a specific item from an array. I was working on a Vue.js app that allows the user to select up to 3 products from a list to view in a side-by-side comparison.
I initialized my array of items to compare by creating an array with a length of 3 with no initial items defined.
const items = Array(3);
Later, I wanted to find an item in the array with a certain id:
const item = items.find((item) => item?.id === checkThisId);
This threw the error Uncaught TypeError: Cannot read properties of undefined (reading 'id')
. I know that each of my items has an id and I even used the optional chaining operator to safeguard against having a null item. So, why the error?
My first thought was that I had a syntax error in my find
that my mind wasn't letting me see. Was my arrow function correct? Was I using Array.find()
correctly? I double checked everything.
I admit that I stared at this for longer than I should have.
Finally, I figured it out. Creating the array with Array(3)
creates an array with a length of 3, but since there is nothing actually set at each index each item is undefined
. So, Array(3)
effectively creates [undefined, undefined, undefined]
(this isn't exactly what is created, but it's functionally the same).
The find
function was iterating through the array explicitly passing undefined
as the item
argument each time.
I fixed it by initializing the array like this:
const items = Array(3).fill(null)
This creates a 3 element array and then sets the value of each element to null
. Now, when the find
is executed now null
is passed which will fail gracefully with the optional chaining operator.
I can't help but think that Typescript would have caught this from the start.