0

The question is, what is the difference between Array(5) and [...Array(5)] See below variable c and d is the same yet .map treats it differently.

let a = [...Array(5)].map((k,i)=>{
  console.log("Hello");
  return i;
})
console.log(a);

let b = Array(5).map((k,i)=>{
  console.log("Hello");
  return i;
})
console.log(b);

let c = Array(5)
let d = [...Array(5)]
console.log(c) // c and d seem to be the same
console.log(d)
13
  • 1
    explain what you mean by using map on Array(5) Commented Mar 3, 2021 at 1:26
  • 2
    Array(5) returns an array with an initial capacity of 5 elements, all of which are empty. [...Array(5)] returns an array with 5 undefined elements. map skips over empty elements. Commented Mar 3, 2021 at 1:30
  • 1
    Does this answer your question? Array.map doesn't seem to work on uninitialized arrays Commented Mar 3, 2021 at 1:30
  • The accepted answer in your linked question is actually not true, map doe snot skip over undefined, this snippet works just fine: [undefined].map(() => {console.log('ayo')}). It specifically does not run in this case because it's empty slots, which is different from undefined. See my answer below. @HereticMonkey Commented Mar 3, 2021 at 1:37
  • 1
    Hopefully this question was clarified. I'm assuming this is easy for full time javascript developers. @Vitim.us Commented Mar 3, 2021 at 5:36

1 Answer 1

1

Because when you directly call Array(5), it creates an empty array, not an array with 5 undefined. This is why nothing happens when you call map because there is nothing for it to iterate over, so it immediately returns.

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), 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). If the argument is any other number, a RangeError exception is thrown.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.