Shallow Comparison

Shallow Comparison in JS

With JavaScript's strict equal operator (===), any Primitive types (strings, numbers, booleans) that have the same value and type are considered equal .

However, for Complex types (array, object) even if they have same properties are considered NOT equal because they take up two distinct address in memory.

// Primitive types (strings, numbers, booleans) are Shallowly Equal
console.log("Hi" === "Hi") // true

// Complex types (array, object) are Shallowly NOT Equal
console.log({name: "Joe"} === {name: "Joe"}) // false

const arr1 = [1, 2, 3]
const arr2 = [1, 2, 3]
console.log(arr1 === arr2) // false

// Comparing two object's properties
const state = {
    favNumber: 42,
    name: "Bob",
    address: {
        street: "123 Main Street",
        city: "Nowhere, PA",
        zip: 12345
    }
}

const state2 = {
    favNumber: 42,
    name: "Bob",
    address: {
        street: "123 Main Street",
        city: "Nowhere, PA",
        zip: 12345
    }
}

// Shallowly equal because we are comparing primitive type's KEY 
console.log(state.favNumber === state2.favNumber) // true
console.log(state.name === state2.name) // true

// Shallowly NOT equal because we are comparing complex type's KEY 
console.log(state.address === state2.address) // false

// Comparing two object's themselves

// These two objects are Shallowly NOT equal 
const person = {
    name: "Sarah"
}

const anotherPerson = {
    name: "Sarah"
}
console.log(person === anotherPerson) // false

// However, These two objects are Shallowly equal since they take same memory adress 
const person = {
    name: "Sarah"
}

const anotherPerson = person
console.log(person === anotherPerson) // true

Last updated

Was this helpful?