Left Arrow.Back

Referential Equality

Table Of Contents

A triangle balancing a straight line on top of it..

Notes on the referential equality in the Javascript programming language.

Last TendedOct 2021
PlantedOct 2021
StatusSeed
TagsJavaScript
The letter 'A' in upper and lower case.

Definition

In JavaScript, if you compare primitive types (string, number, boolean) using the equality operator (===), the results is what you would except:

/index.js

const bool1 = true
const bool2 = false
bool1 === bool1 // result: true
bool1 === bool2 // result: false
const num1 = 1
const num2 = 2
num1 === num1 // result: true
num1 === num2 // result: false
const letter1 = `a`
const letter2 = `b`
letter1 === letter1 // result: true
letter1 === letter2 // result: false

However, if you compare structural types (object, array, function), the result isn't as intuitive:

/index.js

const person1 = {
name: `Deckard`
}
const person2 = {
name: `Deckard`
}
person1 === person2 // result: false
const letters1 = [`a`, `b`]
const letters2 = [`a`, `b`]
letters1 === letters2 // result: false
const function1 = () => null
const function2 = () => null
function1 === function2 // result: false

Take a look at person1 & person2. They are both the same type (object) & 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 structural types, 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.