Search code examples
javascriptvariablesobjectreferenceprimitive

javascript primitives vs object references


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:

  1. If the expression is a primitive, var is defined as a new instance of that primitive with no reference to the passed expression.
  2. If the expression is an object literal, a new object is created.
  3. If the expression is an existing object, 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?


Solution

  • 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.