2019 May 15

Shallow Comparison


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.

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.

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.

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.

Hopefully this is a good enough analogy for explaining this. Say you're in your room and you have a nice collection of music equipment. You point to aGuitar (variable name) which is referencing to gibson335. Conceptually, 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 reason say you had 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.

Copyright © 2021. Jake Wantulok