• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


26 Mar, 2025

Updated at 20 May, 2025

Why all rows be afected when i tried to change once value of array created by fill method in JS?

I created a "pseudo 2D" array using Array() class and fill method, as:

let arr = [...Array(6).fill(Array(3).fill("$"))]

Then, i tried to change only one value with:

arr[3][1] = "hello" 

But when I print the array, all second column be affected. Here the complete code:

let arr = [...Array(6).fill(Array(3).fill("$"))]

arr[3][1] = "hello"

console.log(arr)
// output
[
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ]
]


// expected output

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'hello', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]

Thanks to anyone who can give me an idea why this occur.