javascriptiifeself-invoking-function

Array initialization with self-invoking function


I'm trying to initialize an array with self-invoking function, assume for simplicity as an example, that initial values are squares of numbers from 0 to 4. The new keyword creates new object, so one can access fields of newly created object with this.x or this[x] inside the IIFE body, following the new keyword. The code is:

var arr = new (function() {
    for (var i=0; i<5; i++) { this[i]=i*i; }
})();

Now, you can access corresponding fields of variable arr like arr[4], and get 16. That's perfectly fine if you only work with arr like with an object, but once you try to treat it like an array, you have a problem. Namely, you can't apply functions like reduce to it:

< arr.reduce(...);
> TypeError: arr.reduce is not a function

That's because arr is really an object, not an array:

< arr;
> ({0:0, 1:1, 2:4, 3:9, 4:16})

So here is my question: how to avoid such behavior within this method? How to make JavaScript interpret this newly created object as an array?


Solution

  • Without the IEFE it is shorter and more clear:

    var arr = [];
    for (var i=0; i<5; i++) arr[i] = i*i;
    

    Without the additional counter variable i, you could do:

    for (var arr=[]; arr.length<5; ) arr[arr.length] = Math.pow(arr.length, 2);