0
var a = 0;
jsonArr = [{
   "count" : a
}]
a = 10;
console.log(jsonArr[0].count) 

This doesn't update my JSON values, is there a solution or JSON objects allow no references?

  • 2
    ```jsonArr[0].count = 3;``` is this what you want? – ikhvjs Jun 24 '21 at 13:07
  • 2
    FYI: this isn't JSON but just a plain javascript object. More info on JSON here: [What is JSON and what is it used for?](https://stackoverflow.com/questions/383692/what-is-json-and-what-is-it-used-for) – Reyno Jun 24 '21 at 13:12
  • @Reyno also relevant: [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131) – VLAZ Jun 24 '21 at 13:28

1 Answers1

0

The json.count variable gets assigned to the value of 0, as 0 is a number, and numbers are primitives.

If you used a non-primitive type then the object would hold the reference and the code would work as expected if you edited the object you are referencing.

Just re-assigning a to a different variable will replace that reference in a, pointing to a different object.

See this tutorial for more info on primitives vs non-primitives and by-value vs by-reference, or this example for code that works how you are expecting.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
  • "*If you used a non-primitive type then the object would hold the reference and the code would work as expected.*" [No, it wouldn't](https://jsbin.com/xafonov/edit?js,console). Also, there is no int type in JavaScript. There is number (it's what `a` is) and BigInt. – VLAZ Jun 24 '21 at 13:30
  • Ah yes, sorry about the int confusion, corrected my answer, thanks for pointing that out. The object being referenced would have to have its internals edited, but it is still a reference. re-assigning a variable is different, will add clarity to the answer for that. – Luke Storry Jun 24 '21 at 17:19