1

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]

Sandeep Sihari
  • 97
  • 2
  • 14
  • And yes I have achieved this behaviour using `const x = Array.from(Array(5))` but just wanted to know the reason why above approach is not working. – Sandeep Sihari Dec 30 '21 at 04:38
  • update your question. a comment is a comment – Mister Jojo Dec 30 '21 at 04:41
  • 1
    see also ... [No operation for uninitialized values (sparse arrays)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#no_operation_for_uninitialized_values_sparse_arrays) – Peter Seliger Dec 30 '21 at 05:15

1 Answers1

2

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.
d. Else,
  i. Let intLen be ! ToUint32(len).
  ii. If SameValueZero(intLen, len) is false, throw a RangeError exception.
e. Perform ! Set(array, "length", intLen, true).
f. Return array.

That's all it does, and nothing else. In short, it creates a new array object inheriting from Array.prototype, and then sets a length property on it. It doesn't create any numeric indicies on the array.

It's like

const createArray = (length) => {
  const newArr = Object.create(Array.prototype);
  newArr.length = length;
  return newArr;
};

const arr = createArray(5);
console.log(arr.length);
console.log(arr.hasOwnProperty('0'));

As a result, if you want to iterate over the array, you'll have to fill it first somehow - either with .fill, Array.from, or spreading it into a new array..

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks for the detailed answer this is really helpful. Can you also explain where this is useful? I mean a practical use-case? – Sandeep Sihari Dec 30 '21 at 05:04
  • 1
    I suppose, in rare cases, one would like to create an array with a given large length without also filling all those indicies with values. But that'd be really strange. It's best practice to avoid sparse arrays in all circumstances. I think, if the language was re-designed today, this behavior would be re-examined - it causes far more confusion than the benefits it provides. – CertainPerformance Dec 30 '21 at 05:07