0

I have a forEach() function that increments an array by one for each iteration.

Issue is that every time I print the number variable into the browser's console it shows me its last state instead of the current one. Is this an inconsistency or am I doing something terribly wrong?

Console output

let array = 
[
   {
      "id":1,
   },
   {
      "id":2,
   },
   {
      "id":3,
   }
]

let number = [0]

array.forEach(() => {
    number[0] += 1
    console.log(number)
})
José
  • 33
  • 1
  • 5
  • Here it shows as expected. – Sajeeb Ahamed Jul 12 '21 at 15:44
  • _"it shows me its last state instead of the current one"_ - No, it doesn't. – Andreas Jul 12 '21 at 15:44
  • Im not seeing anything odd about this. Expected behaviour. – Kinglish Jul 12 '21 at 15:45
  • 1
    Previous commenters - look at the snippet output versus your browser console output, that's where the inconsistency is. – lawrence-witt Jul 12 '21 at 15:46
  • The console keeps a *live reference* to the array and shows you the contents of the array as of when you expand it in the console, not as of when it was logged. Since you do that after the code is done, you see the `3` in the array that's there at the end. See the linked question for details. If you want to see the array as it was when it was logged, log a copy, or a JSON string for it (`console.log(JSON.stringify(number))`), etc. – T.J. Crowder Jul 12 '21 at 15:49
  • @T.J.Crowder I didn't consider the concept of live reference. I thought that if I was logging the variable to the console it would keep the state when it was printed. Is there any further reading that I could do on this? Thanks – José Jul 12 '21 at 16:05
  • @José - The [linked question's answers](https://stackoverflow.com/questions/38660832/console-log-of-element-children-shows-0-length-but-has-three-entries-when-expand) are all I can really think of. – T.J. Crowder Jul 12 '21 at 16:49

1 Answers1

0

What you see at the end is the array reference, and at its last state (post forEach). Post running, it is indeed containing one variable with the value 3.

Try to log the value and not the reference and you'll see the "state" of the value.

let array = 
[
   {
      "id":1,
   },
   {
      "id":2,
   },
   {
      "id":3,
   }
]

let number = [0]

array.forEach(() => {
    number[0] += 1
    console.log(number[0]) // <--- this is the diff
})
Aviad
  • 3,424
  • 3
  • 14
  • 21