2

I've stumbled upon something strange.... Maybe someone can try explaining the difference between these two:

var a1=Array(2);
var a2=Array.apply(null,a1);
console.log(a1);
console.log(a2);
console.log(a1[0]===a2[0]);

notice the items are equal but the console log of the arrays looks different (on Chrome and NodeJS).

also other aspects of them seem to work differently:

a1.map(function(i){console.log("!");})
a2.map(function(i){console.log("!");})

notice that map itereares only for a2 not for a1.

this happens on NodeJS, Chrome and FF.

2
  • Without checking the documentation, I'd say that a1=Array(2) sets a1 to an array with length 2, but doesn't explictly assign any elements. Whereas a2=Array.apply(null,a1) is like saying a2=Array(undefined,undefined), i.e., it explicitly sets the value of two elements to undefined. .map() only iterates elements that have been explicitly set. Commented Sep 27, 2014 at 6:23
  • In other words, (I'm guessing that in this case) the key is that someArray[someIndex] will return undefined for two possible reasons: 1. because the element at someIndex was never assigned a value, or 2. because the element at someIndex was explicitly assigned undefined. And your a1[0]===a2[0] test is comparing reason 1 undefined with reason 2 undefined. Commented Sep 27, 2014 at 6:26

1 Answer 1

4

In JavaScript, this creates a sparse array:

var a = new Array(3) // a = [ , , ,]

if you try to iterate over a using map or forEach, JavaScript skips the holes. The invocation

var b = Array.apply(null, Array(3)) // b = [undefined, undefined, undefined]

(this is equivalent to invoking the array constructor with Array(undefined, undefined, undefined))

creates a dense array b. b is almost the same as a but now, you can iterate over the elements, in other words, since the array is now dense, map and foreach don't skip over elements.

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

1 Comment

10x for the pointer.... looked into it further and found you can actually distinguish the two cases with: console.log(0 in a1,0 in a2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.