3

I ran into the following:

// Nothing is printed to console
Array(10).forEach(() => console.log("hi"));

// "hi" is printed 10 times
Array(10).fill(0).forEach(() => console.log("hi"));

Looking at Array constructor docs, the 10 passed in corresponds to the parameter arrayLength with the following documentation:

this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values)

I'm assuming length property indicates how much memory to allocate for the array, but what is an "empty slot" (vs. a slot with undefined or some default value)?

neverendingqs
  • 4,006
  • 3
  • 29
  • 57
  • 1
    A nonexisting slot. A property that does not exist but has an integer name smaller than the `.length` of the array. – Bergi Feb 28 '17 at 22:53
  • 1
    Arrays are just Objects with a special length property and inherited array methods. The *length* property does not necessarily create "empty" slots, ECMA-262 does not specify implementation so developers are free to allocate memory or not, or create empty slots, or not. [*forEach*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-array.prototype.foreach) does not visit "empty" indexes. – RobG Feb 28 '17 at 22:53
  • 1
    Confusingly, calling `fill()` _without an argument_ also works, eg. `Array(10).fill()`. This produces an array with 10 slots _that reference values_ which are `undefined`; subtly different than `Array(10)` which give an array with 10 slots where _the references themselves_ are `undefined`. – Molomby Aug 01 '17 at 01:57

0 Answers0