Brad Woods Digital Garden

Notes / JavaScript / Objects / Referential equality

The Warhammer 40k Adeptus Mechanicus symbol

Table of contents

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

    Referential Equality

    Planted: 

    Tended: 

    Status: decay

    Hits: 106

    Primitives

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

    index.js

    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)

    Objects

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

    index.js

    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 and person2 are both the same type, object. They have the same properties and 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 and person2 may have the same value, but they are 2 different object instances. 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.

    index.js

    // '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;
    b++;
    console.log(a)

    index.js

    // '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;
    d.push(4);
    console.log(c);

    Feedback

    Have any feedback about this note or just want to comment on the state of the economy?

    Where to next?

    JavaScript
    Arrow pointing downYOU ARE HERE
    A Johnny Cab pilot