Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this work? Object references in Javascript

Tags:

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?

like image 605
buzzedword Avatar asked Jun 09 '11 16:06

buzzedword


People also ask

What is object reference in JavaScript?

Objects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory.

What is the purpose of an object reference?

You use an object reference variable to create, manage, and delete objects. It has the data type of a class and, like other variables, is a named area in storage. However, unlike other variables, the value stored in the area is not the object itself but a 4-byte pointer to the object data, called an object reference.

How do references work in JavaScript?

In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

What is the use of this in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.


2 Answers

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.

like image 75
Anurag Avatar answered Oct 28 '22 08:10

Anurag


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.

like image 36
JAB Avatar answered Oct 28 '22 10:10

JAB