0

consider below code

let matrix1 = new Array(2).fill(new Array(2).fill(0));
let matrix2 = [
[0, 0],
[0, 0]
];
console.log(JSON.stringify(matrix1));  //[[0,0],[0,0]]
console.log(JSON.stringify(matrix2));  //[[0,0],[0,0]]
matrix1[0][0] = 5;
matrix2[0][0] = 5;
console.log(JSON.stringify(matrix1));  // [[5,0],[5,0]]
console.log(JSON.stringify(matrix2));  // [[5,0],[0,0]]

when i create matrix with new Array syntax, that values get updated in two elements instead of first one. Is that expected behaviour or am i doing anything wrong

Ravin Singh D
  • 904
  • 10
  • 19
  • 2
    Related: [Weird behaviour in Array.fill](https://stackoverflow.com/questions/40931990/weird-behaviour-in-array-fill) – `.fill()` doesn't clone objects passed to it. It assigns that same object to every index. This means `matrix1` only uses 2 arrays – 1 outer, 1 inner (shown twice). While `matrix2` uses 3 – 1 outer, 2 inner. – Jonathan Lonowski Mar 16 '17 at 04:37
  • @JonathanLonowski can you share any document related to it. what you point out make sense but i want to know moreabout it. MDN dont have info about this same object return concept – Ravin Singh D Mar 16 '17 at 04:45
  • @JonathanLonowski please add this as answer i will accept – Ravin Singh D Mar 16 '17 at 04:47
  • 1
    For a document: [ECMA 262](https://tc39.github.io/ecma262/#sec-array.prototype.fill). It doesn't have a lengthy explanation, but you'll find in it that the ***value*** provided in the first argument is only used once (step 7.b), being set as-is to every index (up to *final*). – Jonathan Lonowski Mar 16 '17 at 04:55

0 Answers0