My loop checks if an array of cards has a special attribute, if so it does a certain action.
if(typeof cardArray[i]['special']!=='undefined'){
// do stuff
}
Unfortunately, even though I'm using typeof to check the array contains a defined special key I'm still getting
Uncaught TypeError: Cannot read properties of undefined (reading 'special')
What am I doing wrong here or is there a better approach for this in general?
As mentioned in the comments, your problem is probably inside your loop.
Take a look at this example running without errors:
const cardArray = [{
'special': 'pasta'
}, {
'regular': 'bread'
}]
for (let i = 0; i < cardArray.length; i++) {
console.log(`Loop number ${i}`)
if(typeof cardArray[i]['special']!=='undefined'){
console.log(`Found: ${cardArray[i]['special']}`)
}
}