0

var state = {
  item1 : {
    text : "hi hi"
  }
}

var i = 5;

function test() {
  state.item1.text = i;
  console.log(state)
  i--
  if (i >= 0) {
    setTimeout(test, 1000);
  }
}

test();

There is a very weird issue where when updating this json object it does not show the correct value. Any help is much appreciated. If I were to console log console.log(state.item1) it would print the correct value. But console.log(state) shows the incorrect value.

Codepen Example http://codepen.io/chrisburgin95/pen/xEzvWz

user94559
  • 59,196
  • 6
  • 103
  • 103
Chris Burgin
  • 236
  • 4
  • 13
  • What do you think is the "correct value" and what are you seeing? The output in the Codepen looks correct to me. – user94559 Oct 13 '16 at 18:37

2 Answers2

2

console.log() does not store a copy of the object. Instead, when you expand nested properties, it will read the current value of each property.

Since your code mutates the same object, expanding the logged objects after all of the timeouts fire will show the final value.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

Objects in Javascript are passed by reference. When the item is printed to the console, you will see the object in its current state, rather than the state it was in when it was printed out. If you were to expand the object in the console, you would see that the text value for state.item1 is 0 for each item logged.

This answer has some good conversation on this subject: Javascript by reference vs. by value

Community
  • 1
  • 1
akosel
  • 1,183
  • 9
  • 14