I was doing some training tasks for my JS course and I got one where you must implement a function that takes a positive integer (n) and returns a matrix like the one below
It's because Array is a reference type. When you do
new Array(n).fill(new Array(n).fill(0))
first the inner new Array(n).fill(0)
makes an array size n filled with 0
; next the outer Array(n).fill
creates an array filled with n references to that inner array.
It doesn't create n inner arrays, just n references to the same array. So when you change an element of that inner array, all the references in the outer array will reflect the change since they all point to the same object.