Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why presize a JavaScript Array?

Firebug represents (new Array(N)) as an array with N undefineds in it. I recently ran across a scenario that demonstrated that a sized array with all undefined values in it is different from a newly constructed, sized array. I'd like to understand the difference.

Suppose you want to generate a list of random integers between 0 and 1000.

function kilorange() {
    return Math.floor(Math.random() * (1001));
}

no_random_numbers = (new Array(6)).map(kilorange);
my_random_numbers = [undefined, undefined, undefined,
                     undefined, undefined, undefined].map(kilorange);

I would have expected no_random_numbers and my_random_numbers to be equivalent, but they're not. no_random_numbers is another array of undefineds, whereas my_random_numbers is an array with six random integers in it. Furthermore, after throwing a console.count statement into kilorange, I learned that my function never gets called for the array created with the Array constructor.

What is the difference, and why does map (and presumably other iterable methods) not treat the above arrays the same?

like image 957
kojiro Avatar asked Oct 16 '11 07:10

kojiro


2 Answers

The ES standard (15.4.4.19) defines the algorithm for map, and it's quite clear from step 8b that since your array doesn't actually have any of those elements, it will return an "empty" array with length 6.

As others have mentioned, it has to do with array objects in js being (unlike their rigid C counterparts) very dynamic, and potentially sparse (see 15.4 for the sparsity test algorithm).

like image 176
davin Avatar answered Nov 08 '22 08:11

davin


When you use:

var a = new Array(N);

no values are stored in the new array and even the index "properties" are not created. That is why map won't do a thing on that array.

The fact that Firebug does that is a bug/feature of the Firebug. You should remember that it's console is an eval envelope. There are other bug/features in the Firebug console.

For example in Chrome console you'll see the above a array as [].

like image 2
ZenMaster Avatar answered Nov 08 '22 06:11

ZenMaster