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
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
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 }
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
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
Happy coding!
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.
Top comments (0)