Skip to content Skip to sidebar Skip to footer

Are JavaScript Array Elements Nothing More Than Array Object Properties?

I have observed the following: var o = {}; // empty JS object var a = []; // empty JS array o.myproperty = 'I am property'; a.push('I am array element'); alert(o['myproperty']);

Solution 1:

Pretty much the only thing an Array adds over an Object is the .length property, and a few array-specific methods like .push. That's really it, under the hood an Array is just an Object. What really makes it usable as an array is said .length parameter; it allows you to iterate the properties in an ordered manner with a for (i = 0; i < arr.length; i++) loop. The .length property is updated when you .push() new elements into the array or when doing some other array-specific manipulations. And that's really all you need to make an object work as an indexed, ordered list.


Solution 2:

To make an accessor value an index in the array it should:

  • Be a non-negative integer (0, 1, 100, 200);
  • If converted to a number (from a string), it should be a non-negative integer ('0', '1.000')

For example:

a['100'] // as index a[100]
a['0']   // as index a[0]
a[1.00]  // as index a[1]

In all other cases the accessor is treated as a property of the array object:

a[-1]       // as a property a['-1']
a['myProp'] // as a property a['myProp']

What makes the array different from regular objects: when using indexes the length property is auto-updated. The length should be always bigger by 1 than the highest index.


Solution 3:

Arrays are Objects, the simplest way to see it is [] instanceof Object which returns true.

And yes, Array elements are accessed by reference the same way Object properties are.

When you delete a property of an Object, you are actually setting this property to undefined, so it's the same for an object or an array.


Post a Comment for "Are JavaScript Array Elements Nothing More Than Array Object Properties?"