Be careful call backing array.fill()

August 05, 2017

Imagine​ filling out an empty 2d array with this

let emptyTwoD = Array(3).fill(Array(3).fill(''))
// emptyTwoD = [['','','']['','','']['','','']]

// tring to change on spot 
emptyTwoD[1][1] = 3
// emptyTwoD = [['', 3,'']['', 3,'']['', 3,'']]

wtf? I just assigned once!

better use map instead

let emptyTwoD = Array(3).fill('').map(e=>Array(3).fill(''))

emptyTwoD[1][1] = 3
// emptyTwoD = [['','','']['', 3,'']['', '','']]

Tagged withjavascript

Questions, Comments, Suggestions? Open an Issue