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 Tended
The letter 'A' in upper and lower case.


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



const bool1 = true
const bool2 = false
console.log(bool1 === bool1)
console.log(bool1 === bool2)
const num1 = 1
const num2 = 2
console.log(num1 === num1)
console.log(num1 === num2)
const letter1 = `a`
const letter2 = `b`
console.log(letter1 === letter1)
console.log(letter1 === letter2)

However, if you compare structural types object, array, function, 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)

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.