ES6 Array.prototype.fill For Object Fix

In ES6, we have Array.prototype.fill method, which will help us to initialize arrays with same values. for example: new Array(5).fill(0) will get [0,0,0,0,0]. it’s a very handy method.

But we when you use it with object, like new Array(5).fill([]), or new Array(5).fill({}), you will probaly got hurt by this method:

let arr = new Array(5).fill({});
arr[0].name = 'test';
console.log(arr);

you will got:

[{name:'test'}, {name:'test'}, {name:'test'}, {name:'test'}, {name:'test'}]

the same are for arrays, as array is object in JS too.

As in JS, objects are passed by reference, and Array.prototype.fill do not consider this diffirence, so it’s impossible to just use fill to create an array of empty objects or arrays.

We can use map to do the same thing actually:

new Array(5).fill(null).map(()=>{})