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

5
  • It seems like you already know the difference. What "background" are you asking for exactly? Commented Sep 27, 2020 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 undefineds, 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. Commented Sep 27, 2020 at 18:08
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 27, 2020 at 18:17
  • @Bergi thank you, your comment and the three duplicates linked are exactly what I needed as background of this phenomenon. Commented Sep 27, 2020 at 18:40
  • @epascarello thanks, super relevant! I should have started with Array.map's docs it seems. Commented Sep 27, 2020 at 18:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.