Unexpected behavior using Array Map on an Array Initialized with Array Fill

Your code is equivalent to:

let inner = Array(3).fill(0);
let M = Array(3).fill(inner);

When you pass inner to .fill(), it doesn't make copies of it, the M array contains 3 references to the same array. So anything you do to one element of M happens to them all.

You need to make new arrays for each element of M:

let M = [];
for (var i = 0; i < 3; i++) {
    M.push(Array(3).fill(0));
}