Search code examples
javascriptarraysmultidimensional-arraynullelement

Safe way to check if array element exists?


I have a 2D array. I currently access that array using notation such as:

myArray[5][9] (for example).

What is the safest way to check whether or not a certain array element exists? For example, let's say I am looping through the array and retrieving a property of each array element like so:

myArray[5][9].firstName

I then come to myArray[9][11].firstName (for example) which doesn't exist. Clearly this will throw an exception as the element doesn't exist.

How can I deal with this? I'm not looping through the entire array (i'm accessing it's contents randomly and say using myArray.lengthin a for loop will not work.

Is there a JS function / method for checking whether or not an array element exists?

Thanks.


Solution

  • like

    if (!('firstname' in myArray[i][j])) { ... }