DEV Community

loading...
Cover image for JavaScript Object References and Copying

JavaScript Object References and Copying

bello profile image Bello ・Updated on ・2 min read


Non-primitive data types like objects can be stored and copied by reference.

See the examples below:

Primitive data type

const name = 'Bello';
const myName = name;

console.log(myName); // Bello
Enter fullscreen mode Exit fullscreen mode

Non-primitive data type

const obj = { name: 'Bello', favNum: 9 }; 
const person = obj; // copy the reference

console.log(person); // { name: 'Bello', favNum: 9 }
console.log(person.favNum); // 9

Enter fullscreen mode Exit fullscreen mode

The object { name: 'Bello', favNum: 9 } is assigned to the variable obj to store its address in memory. Think of obj like a sheet of paper with an address in it. That is, person copied the reference to the object obj.

Accessing the value of the object (person.favNum) looks for the address of obj through person

The object obj itself is not duplicated

We can also modify the object content.

const obj = { name: 'Bello', favNum: 9 }; 
const person= obj; // copy the reference

console.log(person); // { name: 'Bello', favNum: 9 }

person.favNum = 69;

console.log(person); // { name: 'Bello', favNum: 69 }
Enter fullscreen mode Exit fullscreen mode


Comparison by reference

Two objects are equal only if they are the same object.

const a = {};
const b = a; // copy the reference

console.log(a == b); // true, both variables reference the same object
console.log(a === b); // true
Enter fullscreen mode Exit fullscreen mode

Since a and b reference the same object, thus they are equal.

Here also two independent objects are not equal, even though they look alike (both are empty):

const a = {};
const b = {}; // two independent objects

console.log(a == b); // false
Enter fullscreen mode Exit fullscreen mode

Happy coding!


Buy me a Coffee


TechStack | Domain

  • Purchase a .com domain name as low as $9.99.
  • Purchase a .net domain name as low as $12.99.
  • Get cheaper domain names as low as $3.
  • Build a website with ease.

Discussion (0)

pic
Editor guide