DEV Community

Rudra Pratap
Rudra Pratap

Posted on

Working with JS Array Indices

FUN FACT!!
Array indices in Javascript can be integer, float or string!

let a = [1,2]
a[-1] = "negative" 
a[2.5] = "float" 
console.log(a) // [1, 2, -1: 'negative', 2.5: 'float']
Enter fullscreen mode Exit fullscreen mode

How??

Arrays in Javascript are just a special case of objects. That is, an array is just stored as an object behind the scenes.
For example:
[ 1 , 2 ] is stored as [ "1" : 1 , "2" : 2 ]

We can access the array values not just using numberic index, but with strings too.

That is:

let a = [ 1 , 2 ]
console.log( a[1] ) // 2
console.log( a["1"] ) // 2
Enter fullscreen mode Exit fullscreen mode

You will never get "Out of bound" exception in Javascript because, arrays are not really arrays but objects in disguise.

An object can have a maximum of 2^32 -1 properties (key-value pairs), which is the same as the maximum number of items an array can have.

Top comments (0)