Question: I am trying to generate a 2D n\*m array in javascript full of zeros. What is the fastest way of doing that?

I know the simple for loop would be enough to set all the elements to 0, but what I would like to know, why can't I do that with mapping. For example with the underscore lib (or even the native map)

```
_.map(Array(n),function(a){return 0}) // makes {undefined,undefined,...}

```

while

```
_.map([1,2,3,5,6],function(a){return 0}) // makes {0,0,0,0,0}

```

Can anyone explain if I can fill an empty array with a map function and how, or why not?

PS: There is a trivial solution to my problem, I am just asking this cause I would like to learn more, and I cant find a good enough answer on google. Thank you

Answer: 
Typical JavaScript `.map()` functions ignore array members that are `undefined`. That's why `Array(n)` doesn't work.

---

You could easily add a method to `Array.prototype` to do a quick fill...

```
Array.prototype.fill = function(n,v) {
    n = n || this.length;
    for( var i = 0; i < n; i++ ) 
        this[i] = v === void 0 ? i : v;
    return this;
};

```

then...

```
Array().fill(3); // [0,1,2]

Array().fill(3, 0); // [0,0,0]

```
A simple trick may be:

```
var myarr = '0000000000'.split('');

```

Another is to make your own map Array extension, to be able to work with `Array(n)`:

```
Array.prototype.mapx = function(callback){
  return this.join(',').split(',').map(callback);
}
//usage
Array(5).mapx(function(){return 0;}); //=> [0,0,0,0,0]

```

I'd think the first one is the fastest, but no time (now) to test it.