6

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?

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That makes a LOT more sense seeing it like that. Thanks!
3

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.

8 Comments

So what you're saying then is, that (as Anurag pointed out) using a Native type will implicitly create a new object, whereas reassigning the object to another variable simply makes a reference-- unless the new keyword is explicitly used?
This is not strictly correct. The values assigned to a and b are not objects.
@Buzzedword: Something like that.
@lawnsea: Hence why I changed it to "object/value" rather than just "object".
@Buzzedword @JAB - No. See Anurag's explanation and my annotation of your code sample. The new operator has nothing to do with this.
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.