In the realm of JavaScript, it's important to understand that there are no true multi-dimensional arrays. While you can create an array element that contains another array and work with it, all references you make need to account for this.
For example, you can initialize an array like so:
arr = [];
arr['house'] = [];
arr['house']['rooms'] = 2;
However, trying to set a value for arr['house']['rooms']
without previously defining arr
and arr['house']
will result in an error.
If you want to avoid errors when dealing with multiple levels of reference, you'll need to ensure that all the levels exist before accessing them.
Arrays vs Objects
Arrays and objects share similarities and can both be accessed using []
notation, but technically you are utilizing the object aspect of arrays in this context. Although arrays can do what objects can do, plus more, they only work with numeric indices. When you use a string to reference an array, you are essentially trying to access a member of the underlying object that matches that string.
Ultimately, there are no true multi-dimensional arrays or objects. Using []
notation with objects is merely a way to check for object members using a variable. arr['plane']['rooms']
is equivalent to arr.plane.rooms
, but visually, arr.plane.rooms
may help clarify why you need to first check arr.plane
(and arr
).