Skip to content Skip to sidebar Skip to footer

Js Array A['1'] Doesnot Gives An Error

I have declared an array a = [1,2,3,4,5] When I write a[1] it returns 2 which is perfectly fine but when I write a['1'] it also gives me 2 instead of giving an error. I was expec

Solution 1:

All property names are strings.

If you pass a number, it gets converted to a string before being used to look up the property value.

console.log(1 == '1');

Solution 2:

In JS an Array is basically an Object and thus mostly behaves like one. In this case, these are equivalent as long as you dont access Array's .length or try iterating a:

const a = {"0": foo};    
const b = ["foo"];

Also this would work:

const a = ["foo"];
a.bar = "baz";

console.log(a);

So that a[1] and a['1'] are equivalent is exactly what's to be expected.

Solution 3:

First of all, array is also object having property names as 0,1,2,....n

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method. [Ref]

Post a Comment for "Js Array A['1'] Doesnot Gives An Error"