15

Consider the following JavaScript code (in a node REPL):

> let a = new Array(10)
undefined
> a
[ <10 empty items> ]
> a.map(e => 1)
[ <10 empty items> ]
> let b = new Array(10).fill(undefined)
undefined
> b
[ undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined ]
> b.map(e => 1)
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
> 

When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Wickoo
  • 6,745
  • 5
  • 32
  • 45

2 Answers2

11

When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?

That's because Array(10) doesn't populate the array. But it just set the length property to 10 .So, the array created using Array constructor is simply an object with a length property, but with no items populated.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
9

That's because undefined is a value, while when you create an array for example like this:

var array = [];
array.length = 10;
console.log(array);
>(10) [empty × 10] // in google chrome

10 empty slots are created. The empty slot is different from the undefined value, and the most important difference is that the empty slot is not Enumerable.

var mappedArray = array.map(x => 1);
console.log(mappedArray);
>(10) [empty × 10] // in google chrome

Since map function enumerates the values in the orriginal array and returns the array of the same length, it has no effect on the array of 10 empty slots.

Note that empty slots are named differently in different browsers.

  • 5
    The formal name is *Ellision* http://www.ecma-international.org/ecma-262/6.0/#sec-array-initializer – Kaiido May 14 '18 at 08:53