32

I can use Array() to have an array with a fixed number of undefined entries. For example

Array(2); // [empty × 2] 

But if I go and use the map method, say, on my new array, the entries are still undefined:

Array(2).map( () => "foo");  // [empty × 2] 

If I copy the array then map does work:

[...Array(2)].map( () => "foo");  // ["foo", "foo"]

Why do I need a copy to use the array?

cham
  • 8,666
  • 9
  • 48
  • 69
  • what is the result of `[...Array(2)]` – Kain0_0 Nov 27 '18 at 02:39
  • @Kain0_0 It is [undefined, undefined]. And Array.isArray(Array(2)) is true. – cham Nov 27 '18 at 02:41
  • 3
    Can use `fill()` also. `Array(2).fill("foo"); // ["foo", "foo"]` Just have to be careful with passing object to fill as all elements will be same reference – charlietfl Nov 27 '18 at 02:54
  • 3
    Possible duplicate of [JavaScript "new Array(n)" and "Array.prototype.map" weirdness](https://stackoverflow.com/questions/5501581/javascript-new-arrayn-and-array-prototype-map-weirdness) – Patrick Roberts Dec 03 '18 at 18:42
  • There's nothing like _index out of bound error_ in JavaScript. – Igwe Kalu Feb 09 '19 at 22:28

4 Answers4

54

When you use Array(arrayLength) to create an array, you will have:

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).

The array does not actually contain any values, not even undefined values - it simply has a length property.

When you spread an iterable object with a length property into an array, spread syntax accesses each index and sets the value at that index in the new array. For example:

const arr1 = [];
arr1.length = 4;
// arr1 does not actually have any index properties:
console.log('1' in arr1);

const arr2 = [...arr1];
console.log(arr2);
console.log('2' in arr2);

And .map only maps properties/values for which the property actually exists in the array you're mapping over.

Using the array constructor is confusing. I would suggest using Array.from instead, when creating arrays from scratch - you can pass it an object with a length property, as well as a mapping function:

const arr = Array.from(
  { length: 2 },
  () => 'foo'
);
console.log(arr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I saw `Array()` in a course and it reminded me of something useful in Python, But sadly it's maybe it's not so useful. Cheers. – cham Nov 27 '18 at 02:45
  • 1
    It *used* to be a decent option, before `Array.from` was available, but now I don't think there's any reason to use it, it has too much potential for confusion. – CertainPerformance Nov 27 '18 at 02:46
  • Hey Need you help here https://stackoverflow.com/questions/68834433/how-to-promisify-using-providing-some-limit Pls – Profer Aug 18 '21 at 14:45
10

The reason is that the array element is unassigned. See here the first paragraph of the description. ... callback is invoked only for indexes of the array which have assigned values, including undefined.

Consider:

var array1 = Array(2);
array1[0] = undefined;

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(array1);
console.log(map1);

Outputs:

Array [undefined, undefined]
Array [NaN, undefined]

When the array is printed each of its elements are interrogated. The first has been assigned undefined the other is defaulted to undefined.

The mapping operation calls the mapping operation for the first element because it has been defined (through assignment). It does not call the mapping operation for the second argument, and simply passes out undefined.

Kain0_0
  • 319
  • 2
  • 6
2

As pointed out by @CertainPerformance, your array doesn't have any properties besides its length, you can verify that with this line: new Array(1).hasOwnProperty(0), which returns false.

Looking at 15.4.4.19 Array.prototype.map you can see, at 7.3, there's a check whether a key exists in the array.

1..6. [...]
7. Repeat, while k < len

  1. Let Pk be ToString(k).

  2. Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk.

  3. If kPresent is true, then
    1. Let kValue be the result of calling the [[Get]] internal method of O with argument Pk.

    2. Let mappedValue be the result of calling the [[Call]] internal method of callbackfn with T as the this value and argument list containing kValue, k, and O.

    3. Call the [[DefineOwnProperty]] internal method of A with arguments Pk, Property Descriptor {[[Value]]: mappedValue, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}, and false.

  4. Increase k by 1.

9. Return A.
Moritz Roessler
  • 8,542
  • 26
  • 51
0

As pointed out already, Array(2) will only create an array of two empty slots which cannot be mapped over.

As far as some and every are concerned, Array(2) is indeed an empty array:

Array(2).some(() => 1 > 0); //=> false
Array(2).every(() => 1 < 0); //=> true

However this array of empty slots can somehow be "iterated" on:

[].join(','); //=> ''
Array(2).join(','); //=> ','

JSON.stringify([]) //=> '[]'
JSON.stringify(Array(2)) //=> '[null,null]'

So we can take that knowledge to come up with interesting and somewhat ironic ways to use ES5 array functions on such "empty" arrays.

You've come up with that one yourself:

[...Array(2)].map(foo);

A variation of a suggestion from @charlietfl:

Array(2).fill().map(foo);

Personally I'd recommend this one:

Array.from(Array(2)).map(foo);

A bit old school:

Array.apply(null, Array(2)).map(foo);

This one is quite verbose:

Array(2).join(',').split(',').map(foo);
customcommander
  • 17,580
  • 5
  • 58
  • 84