I've been using JavaScript for years and this one has me stumped. As I understood things, when defining a var
, one of two things will happen:
var
is defined as a new instance of that primitive with no reference to the passed expression.var
will reference the object and any future changes to the object will be reflected.However, I've run into a situation where case 3 doesn't apply:
var obj = {body: {'a': 1, 'b': 2, 'c': 3}};
var ref = obj.body;
ref = JSON.stringify(ref);
console.log(typeof ref); // string
console.log(typeof obj.body); // object
Since ref
is defined as the body
property of obj
, I thought redefining ref
as a string also would affect obj.body
. So what am I missing?
JSON.stringify
is a method which takes an object and returns its string representation, it doesn't change anything. By doing ref = x
you make ref
point to another thing, it doesn't affect what was there before assignment.