Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get Array length

See below given scenario

var x = [];
x['abc'] = "hello";
console.log(x.length); //returns 0

var x = [1,2];
x['abc'] = "hello";
console.log(x.length); //returns 2

Any reason behind this or Am i missing anything?

like image 718
Aju John Avatar asked Oct 30 '25 03:10

Aju John


1 Answers

As per spec

The value of the length property is numerically greater than the name of every own property whose name is an array index; whenever an own property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant.

Further

Specifically, whenever an own property is added whose name is an array index, the value of the length property is changed.

So, length property is adjusted when the property whose name is an array index is created, only then length property changes.

'abc' being a non-numeric (and hence not an index of an array) when added to the array, doesn't reflect any change in length property.

like image 53
gurvinder372 Avatar answered Nov 01 '25 17:11

gurvinder372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!