0

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?

dux0r
  • 89
  • 1
  • 1
  • 5
  • Are you looking for [Optional chaining (`?.`)](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Optional_chaining)? – Sebastian Simon Nov 18 '21 at 15:26
  • 2
    If special is undefined, are you sure that `i` isn't going past the bounds of the array? – Rory McCrossan Nov 18 '21 at 15:31
  • Once you need to check all your array elements have values because value at some index of array is coming undefined. – Anuj Raghuvanshi Nov 18 '21 at 15:34
  • 2
    It's `cardArray[i]` that's undefined, not `cardArray[i]['special']`. The error is because you're attempting to access `undefined.special`. – ray Nov 18 '21 at 15:38
  • Take a look at [this related question](https://stackoverflow.com/q/54646467/6532549). _Disclaimer: I wrote the accepted answer._ – yqlim Nov 18 '21 at 15:40

1 Answers1

0

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']}`)
  }
}
LSE
  • 1,075
  • 1
  • 8
  • 10