Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Why is Array.map returning different results?

According to my current JS understanding, All 3 lines below should return the same result, can someone please explain what I'm missing ?

1- Unexpected

[...Array(6).map((x) => 1)]
(6) [undefined, undefined, undefined, undefined, undefined, undefined]

2- expected

[...Array(6)].map((x) => 1)
(6) [1, 1, 1, 1, 1, 1]

3- unexpected

Array(6).map((x) => 1)
(6) [empty × 6]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Array(n) creates an array of length n, but the array has no values in it so there is nothing to map over.

Basically, this:

const a = Array(n);

is the same as:

const a = [];
a.length = n;

This is why the created array has no elements in it. Attempting to map it will do nothing since there are no values to map.

You can, however, convert that empty array to an array of undefined values. This can be done in two ways:

One is using the spread operator as you have done:

[...Array(n)] // creates new array [undefined, undefined, undefined ...] n times

The other, more commonly used, is .fill(), which sets its parameter as the value for all the indices of the array. To fill with undefined, do:

Array(n).fill() // fills array with [undefined, undefined, undefined ...] n times

An array of undefined, unlike an empty array, has elements and can therefore be mapped:

[undefined, undefined, undefined].map(x => 1) // [1, 1, 1]

So you can first convert your empty array to an array of undefined, and then map it like so:

Array(n).fill().map(x => 1)

If you want to fill the array with the same element in each position like in this example, you can simply pass it in to fill without needing to map the array:

Array(n).fill(1)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!