Home > front end >  Why an empty array of N length in javascript does not have indices?
Why an empty array of N length in javascript does not have indices?

Time:12-31

So I have created an empty array in Javascript

const x = Array(5);

Or

const x = new Array(5);

And if i check the length, Its 5 in both the cases but when I loop over it using .map then it did not give me the indices i.e 0,1,2,3,4

x.map((el, i) => i);

This should return [0,1,2,3,4]

CodePudding user response:

Because the specification requires that when an array is created like that with the Array constructor, where values is the argument list:

a. Let len be values[0].
b. Let array be ! ArrayCreate(0, proto).
c. If Type(len) is not Number, then
  i. Perform ! CreateDataPropertyOrThrow(array, "0", len).
  ii. Let intLen be 1           
  • Related