I was trying to used Array.prototype.fill method to create a n x n 2D array but the code was buggy and I eventually found out all arrays inside are actually
This is because when you're calling array.fill() you're only passing it a single new Array() value. That's the point, to fill an array with a single value.
If you want to take an existing array and assign a new instance to each index you could use .map().
var matrix = new Array(10).fill().map(function(item, index, arr) {
return new Array(10);
});
To do this in the nested fashion you seem to want you can map twice.
// the callback function's item, index and array properties are optional
var matrix = new Array(10).fill().map(function(item, index, arr) {
return new Array(10).fill(0);
});
If you're using ES6, this can be further simplified to a one-liner.
var matrix = new Array(10).fill().map(() => new Array(10).fill(0));
The reason .map() works is because it calls the supplied callback function for each item in the array.
The reason for the blank .fill() before the .map() is to populate the array with values. By default a new array that's been given a size has undefined for every item. .fill() will temporarily populate the array so it can be mapped.