1

I have a question about js loops and how they really work. I'm looping trough an array of objects that looks like this:

const array = [{value: 0}, {value: 0}, {value: 0}, {value: 0}];

The loop just updates the value of every element:

array.forEach(el => {
        el.value = 1;
        console.log(array)
})

The thing that I don't understand is why the output looks like this:

[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]

And not like this:

[{value: 1}, {value: 0}, {value: 0}, {value: 0}]
[{value: 1}, {value: 1}, {value: 0}, {value: 0}]
[{value: 1}, {value: 1}, {value: 1}, {value: 0}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]

What am I missing?

matteo
  • 115
  • 1
  • 7

1 Answers1

5

I'm guessing that you are trying to look at the output on the dev tools on Chrome, and on the dev tools, you see a reference to the array. meaning that at the end of the execution all the items have value = 1, so the dev tools shows your the same reference to the array.

To see the actual values at the moment of execution (instead of reference) use JSON.stringify like this:

const array = [{value: 0}, {value: 0}, {value: 0}, {value: 0}];

array.forEach(el => {
        el.value = 1;
        console.log(JSON.stringify(array))
});
gilamran
  • 7,090
  • 4
  • 31
  • 50