0

What is the difference between the undefined elements in JavaScript arrays:

  1. created directly,
  2. created with elision?

Elements of case 1. and 2. both have undefined types and values, but the ones born in elision don't have indexes (or any enumerable properties, their array has a correct Array.length that's clear). Can you give some background on this?

Example:

// case 1.
const undefineds = [undefined, undefined, undefined].map((el, i) => i)
console.log(undefineds, undefineds.length, 'undefineds')

// case 2.
const empties = [,,,].map((el, i) => i)
console.log(empties, empties.length, 'empties')

Output:

Array [0, 1, 2] 3 "undefineds"
Array [undefined, undefined, undefined] 3 "empties"

Note: In case 2. I am aware of not just the indexes i would be undefined, but anything returned from the iteration, e.g.: [,,,].map((el, i) => 'puppies') => [undefined, undefined, undefined].

theDavidBarton
  • 7,643
  • 4
  • 24
  • 51
  • It seems like you already know the difference. What "background" are you asking for exactly? – Bergi Sep 27 '20 at 18:04
  • 1
    Notice that when you `map` over an array with elisions, the point is that the callback doesn't get called at all on the non-existing elements. It's not like it's called with `undefined` for the value and `undefined` for the index. Also, it does not return an array of `undefined`s, it does return another sparse array - your `console.log` implementation appears to be confused by that though. It should log `[,,,]` or `[empty, empty, empty]` or [something like that](https://stackoverflow.com/q/10683773/1048572). – Bergi Sep 27 '20 at 18:08
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description – epascarello Sep 27 '20 at 18:17
  • @Bergi thank you, your comment and the three duplicates linked are exactly what I needed as background of this phenomenon. – theDavidBarton Sep 27 '20 at 18:40
  • @epascarello thanks, super relevant! I should have started with `Array.map`'s docs it seems. – theDavidBarton Sep 27 '20 at 18:44

0 Answers0