1

I tried this in the chrome dev tools console:

let a = [[null,null],[null,null]]

function na(){ return Array(2).fill(Array(2)) }
let b = na();

console.log(JSON.stringify(a))
// [[null,null],[null,null]]

console.log(JSON.stringify(b))
// [[null,null],[null,null]]

So far, so good. I was expecting both a and b with the same values and strucuture. Then I wanted to test a small function that should append an extra value in each line:

function add(x) { x.map( line => line.push(null) )}

add(a)
console.log(JSON.stringify(a))
// [[null,null,null],[null,null,null]]

add(b)
console.log(JSON.stringify(b))
// [[null,null,null,null],[null,null,null,null]]
// ?! I was not expecting this extra value here...

Well, that was unexpected. Why is that extra null appearing in add(b) ?

João Otero
  • 948
  • 1
  • 15
  • 30

1 Answers1

0
function na(){
    return Array(2).fill(Array(2))
}

na() fills the empty Array(2) with shallow copies of the second Array(2) object.

As a result changing values in any of the clones changes the Array's value everywhere.

a = Array(5).fill(Array(3))

a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

console.log(JSON.stringify(a))

So because b has 2 elements and you are using .push() to add an element to b for each of the (same) arrays, 2 new elements are added to the array.

lejlun
  • 4,140
  • 2
  • 15
  • 31