Left ArrowBack

notes / JavaScript / objects / referential equality

referential equality

Ani's soul, represented by a bird with a human head, observes as Anubis weighs Ani's heart.

Referential Equality

Last Tended

Status: sprout


If you compare primitive types; null, undefined, string, number, boolean or symbol using the equality operator ===, the results is what you would except:



const bool1 = true
const bool2 = true
console.log(bool1 === bool1)

const num1 = 1
const num2 = 1
console.log(num1 === num2)

const letter1 = `a`
const letter2 = `a`
console.log(letter1 === letter2)


If you compare objects object, array, function (arrays & functions are a sub-class of object), the result isn't as intuitive:



const person1 = {
    name: `Deckard`
const person2 = {
    name: `Deckard`
console.log(person1 === person2)

const letters1 = [`a`, `b`]
const letters2 = [`a`, `b`]
console.log(letters1 === letters2)

const function1 = () => null
const function2 = () => null
console.log(function1 === function2)

person1 & person2 are both the same type object. They have the same properties & values. It would makes sense if the equality operator returned true when comparing them, but it doesn't. This is because when you compare objects, the operator is testing reference equality, not value equality. Testing whether they are the same instance, not whether they are the same value. person1 & person2 may have the same value, but they are 2 different object instances. If I change a property on 1, the other will remain the same. Thus, when compared using the equality operator, it returns false.

2 characters in an arcade game about to fight.

Value vs. Reference

When assigning or passing variables of a primitive, a copy of the value is created. When assigning or passing variables of an object, a copy of the reference is created.



// 'a' holds a copy of the value 2. 
// 'b' is assigned a copy of the value 2. 
// Any changes to 'b' will not effect 'a'.
var a = 2;
var b = a;



// 'c' holds a reference to the shared value '[1, 2, 3]'
// 'd' holds a copy of the reference to shared value '[1, 2, 3]'
// When using the 'd' reference to modify the shared value, 'c' will be effected.
var c = [1,2,3];
var d = c;

Where to Next?

A sci-fi robot taxi driver with no lower body