What is Shallow Comparison?

Use of Strict

With Primitive Types (strings, numbers, booleans), using strict (triple) equals === checks the type, then checks the value/memory. This works to ensure that one primitive is the same as another.

// Primitive types (strings, numbers, booleans);
console.log("Hi" === "Hi");
> true

However, this is not helpful for Complex Types (arrays, objects). This is because they are considered with distinction and hold memory separately, even if they look the same.

// Complex types (array, object)
console.log({name: "Joe"} === {name: "Joe"});
> false

Use Shallow Comparison for Complex Types

So how should we go about checking complex types? Compare the values (which are primitive types) of the keys.

const objOne = {
    name: "Jake",
    favClr: "blue"
}

const objTwo = {
    name: "Jake",
    favClr: "blue"
}

console.log(objOne.name === objTwo.name);
> true

This is considered as a shallow comparison. Because we're looking at objects just below the surface level.

Pointers

Keep this in mind that a pointer is not the same as a object that holds space in memory, but rather points to an object.

const gibson335 = {
    name: "Lucille",
    manufacturer: "Gibson",
    model: "ES-335",
    color: "black",
    modifications: ["thinline hollow-body", "no f-holes", "maple-neck"]
}

const thatGuitar = gibson335;

console.log(thatGuitar === gibson335);
> true

Hopefully this is a good enough analogy for explaining this. Say your mom isn't interested in guitars and you know all about them. She points to a guitar in the living room and asks you to put away " thatGuitar " (variable name) and you respond, "Do you mean, my gibson335 (object) named 'Lucille' (gibson335.name)?" She says "Yes (true), just put it away." There is only one object that is in possession/memory with a variable name, and the other variable name does not have possession of the object, but simply refers or points to the object.

Now for some odd reason say you add two identical guitars? This would be the same as two unique objects. Just like with our eyes they may look exactly the same doesn't mean they are, JavaScript also understands this distinction. If it takes up space it is considered an object.

Where Shallow Comparison Can Hurt You

When we are shallowly comparing primitive types in objects, we might not be checking deep enough to know for sure.

const person = {
    name: "Jake",
    features: {
        eyeClr: "green"
    }
}

const anotherPerson = {
    name: "Jake",
    features: {
        eyeClr: "blue"
    }
}

console.log(anotherPerson.name === person.name);
> true

console.log(anotherPerson.features.eyeClr === person.features.eyeClr);
> false
Copyright © 2020. Jake Birkes