4

When I console.log my array before and after changing it with foreach, it works as expected for a simple array of numbers, but for an array of objects, the console.log before the foreach logs the array after having been changed, unlike the array of numbers. Please can you help me understand what causes this behaviour?

const simplearray = [1, 2, 3]
console.log(simplearray) // returns [1,2,3]
simplearray.forEach((d, i) => simplearray[i] = d + 10)
console.log(simplearray) // returns [11,12,13]

const objarray = [{
  n: 1
}, {
  n: 2
}, {
  n: 3
}]
console.log(objarray) // returns [{"n":11},{"n":12},{"n":13}]
objarray.forEach(d => d.n = d.n + 10)
console.log(objarray) // returns [{"n":11},{"n":12},{"n":13}]

Update: I can confirm that logging the object with JSON.Stringify(), as suggested in the duplicate question linked to, correctly logs the before and after of the object.

Max888
  • 3,089
  • 24
  • 55

0 Answers0