1

In Chrome Version 125.0.6422.76 (Official Build) (64-bit), I'm seeing this weird behavior with the Array constructor:

Javascript: Array(3).map() vs [...Array(3)].map() weird behavior

Notice that a's length is correctly stored as 3 internally.

I care less if Javascript is doing an internal optimization by lazily allocating the 3 (or more) elements later (say, during element assignment) as long as an array of length 3 is returned as an object for the map call in a.map().

Apparently, it isn't, since no foo's get printed as they do with b.map().

5
  • you cannot iterate when created using Array constructor stackoverflow.com/a/41246860 Commented May 25, 2024 at 6:55
  • 3
    developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… empty slots are skipped during iteration Commented May 25, 2024 at 7:02
  • 5
    .map() skips over empty element, and spread syntax replace the empty element with undefined Commented May 25, 2024 at 7:12
  • 2
    Read about sparse arrays Commented May 25, 2024 at 7:17
  • Thanks, sparse arrays and definitions of map vs join etc is the real answer. Thanks, to all those who took the time to respond. Commented May 25, 2024 at 8:07

1 Answer 1

1

When you initialize an array using Array constructor, it's an empty array. Yes, it has an length, which means JS stored a block of memory for the future use cases but it is completely empty. So, there is nothing to iterate over.

In the your second case, b array, there is an array with undefined elements. So, you can iterate over it.

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.