Home > JavaScript > Secrets of Javascript Arrays

Secrets of Javascript Arrays


Secrets of Javascript Arrays

Arrays are a common structure in many languages, It’s a sequence of values that you wanna access in an indexed-based way. Let’s define an array.

var myArray=[100,200,300];

A point to note that Javascript arrays are zero-based (well of course nothing new!).

But what’s the secret. Let’s raise the curtains.

What if I say to calculate the length of the array.


That’s it, just access the length property of the array. Wait a minute, where the hell this length property came from. You guessed it right, it’s an object. An array is actually an object of Javascript (it’s readymade). Indexes and length are properties of the array object.

What if I do myArray[0]. We get 100.

And what if I do myArray[“0”]. We will get the same 100. People who know object-oriented javascript know that [“<propertyName>”] is another way of accessing the property. So, this also proves that arrays are objects. But if it is an object, why not use indexes in dot(.) notation like myArray.0. Wrong, if the property happens to be number data-type then we cannot use dot(.) notation instead we will have to use square bracket([]) notation. But wait a minute here we are accessing values as myArray[0], type coercion comes into action internally Javascript converts myArray[0] to myArray[“0”].

Let’s see some more magic. For the above array of length 3 what if I do,


Since objects in Javascript is free form, so no problem here, you can put anything of anything type. But, what will be the length of the array here, ideally it should be 4 but it prints 401. Actually, Javascript arrays for length property value adds 1 to the last index. Strange!

You can also do,

Again, the length will be the same 401. And, do not worry about index-like objects property names can also be of string type.

About jkoder