2

We all know the difference between array literals and array constructors is subtle but can be important. There seems to be another difference that is not noted in the referenced link. Take the following:

var x = new Array(5); // [undefined x 5];
var newArr = x.map(function () {return 'newValue'});
console.log(newArr); // [undefined x 5];

vs

var y = [undefined, undefined, undefined, undefined, undefined];
var newArr = y.map(function () {return 'newValue'});
console.log(newArr); // ['newValue', 'newValue', 'newValue', 'newValue', 'newValue'];

I would expect x and y to both be array instances and return the same result from the .map method. Seemingly oddly though, the array x produces an array that is not mappable whilst the literal y is mappable.

Why does x and y return different results from the .map method?

Thanks for any help.

Community
  • 1
  • 1
nikk wong
  • 6,691
  • 5
  • 42
  • 60
  • Arrays created by the Array constructor by passing in a number, are not iterable with array methods, such arrays have a length, but no values, they are literally undefined. – adeneo Mar 09 '16 at 00:04
  • http://stackoverflow.com/questions/32305179/whats-the-difference-between-undefined-undefined-and-new-array2 – Bergi Mar 09 '16 at 00:05
  • @adeneo—or literally not defined. ;-) – RobG Mar 09 '16 at 00:20

1 Answers1

3

MDN:

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

Amit
  • 41,690
  • 8
  • 66
  • 101