Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 929
Jordan Avatar asked Feb 01 '15 14:02

Jordan


1 Answers

Safe call operator ?. looks fine. Warning: many, but not all implementations (and versions) of JavaScript supports it.

For your example it will looks like

myArray[5][9]?.firstName

EDIT: Thanks to Asaf comment there is more safe version

myArray?.[5]?.[9]?.firstName
like image 100
DropDrage Avatar answered Sep 27 '22 19:09

DropDrage