Fill javascript function gives unpredictable result

Viewed 26

Today played with JS and found out strange thing with using spread syntax and fill() function. So here is my code:

     let v = [...Array(9).fill([])];

        function myFunc(){
         arr = [1,5,2,3,4,6,8,9,7];
     
        arr.map((val, i)=> {
             v[i].push(val);
        });  
    }

   myFunc();

Result i've got with v-array:

Array(9) [ (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […] ]
​
0: Array(9) [1,5,2,3,4,6,8,9,7]
​
1: Array(9) [1,5,2,3,4,6,8,9,7]
​
2: Array(9) [1,5,2,3,4,6,8,9,7]
​
3: Array(9) [1,5,2,3,4,6,8,9,7]
​
4: Array(9) [1,5,2,3,4,6,8,9,7]
​
5: Array(9) [1,5,2,3,4,6,8,9,7]
​
6: Array(9) [1,5,2,3,4,6,8,9,7]
​
7: Array(9) [1,5,2,3,4,6,8,9,7]
​
8: Array(9) [1,5,2,3,4,6,8,9,7]
​

So it basicaly each sub array filled subsiqently or wit same amount of numbers. I am not quite sure how it works. But when i used instead:

 let v = [...Array(9).fill([])];

just simple:

let v = [[],[],[],[],[],[],[],[],[]];

All was fine. That worked as supposed it be.

Array(9) [ (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […] ]
​
0: Array [ 1 ]
​
1: Array [ 5 ]
​
2: Array [ 2 ]
​
3: Array [ 3 ]
​
4: Array [ 4 ]
​
5: Array [ 6 ]
​
6: Array [ 8 ]
​
7: Array [ 9 ]
​
8: Array [ 7 ]

It`s just more like notice for those who will use same thing as i do, but if someone can explain me this phenomenon i will really appreciate it.

1 Answers

That's because when you're doing this:

let v = [...Array(9).fill([])];

You're filling the array with the same empty array.

An equivalent to your code would be:

const EMPTY_ARRAY = [];

let v = [...Array(9).fill(EMPTY_ARRAY)];

And later, when you're pushing the elements — you're pushing them to the same array (EMPTY_ARRAY).

You can ensure that it's the same array if you compare the elements of that array:

let v = [...Array(9).fill([])];

console.log(v[0] === v[1])
Related