DEV Community

Cover image for JavaScript Object References and Copying
Bello Osagie
Bello Osagie

Posted on • Edited on

2 1

JavaScript Object References and Copying


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

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay