buzzedword
buzzedword

Reputation: 3178

Why does this work? Object references in Javascript

I've finally been curious enough to find out why javascript does its voodoo magic to learn why not all object references are created equal.

Given the example:

var a, b, c, d;
a = 100; b = a;

c = {}; d = c;

b = 10; d.e = 'f';

console.log(a, b); // outputs 100, 10
console.log(c, d); // outputs object => e = 'f', object => e = 'f'

If all variables in javascript are objects, then what makes the use case with c and d cast explicitly as an Object so different than defining a and b as Number? Or, why will c and d be linked to one another, and not a and b?

Upvotes: 6

Views: 1891

Answers (3)

lawnsea
lawnsea

Reputation: 6581

The value of a that is assigned to b is a Number. The value assigned from c to d is a reference to an Object.

var a, b, c, d;
a = 100; // a has value 100, a number
b = a; // b has value 100, a number

c = {}; // c has value p, a reference to some object P
d = c; // d has value p, a reference to P

b = 10; // b has value 10, a number
d.e = 'f'; // P.e has value 'f', a string

Upvotes: 2

Anurag
Anurag

Reputation: 141909

All variables in JavaScript are not objects. There are native types as well.

c and d are not linked to one another. They are pointing to the same object reference. If you were to reassign d to something else, it will not affect c.

var c = {};
var d = c;
d = { foo: "bar" };

c === d // false

However, if you were to modify the object being referenced by c or d, it will modify the same object since c and d are both referring to the same object as in your example.

Upvotes: 8

JAB
JAB

Reputation: 21089

It looks to me that the difference is with b, you're reassigning the variable to a new object/value, while with d, you're modifying the existing object.

Upvotes: 3

Related Questions