Shallow & Deep Comparison

Marcos Gonçalves
NERDJACKING
Published in
2 min readMay 29, 2021

Different strategies to compare operands data type and value equality.

You most likely have heard those terms before, but in case you haven’t, let’s get some concepts rights:

Shallow & Deep Comparison

They are a technic to solve comparison problem that the basic JavaScript Operators can’t solve by itself alone, like comparing if two objects are both equal in data type, size and value.

And as you probably have guessed, shallow strategy compares superficially 2 operands equality — 1st level in depth only— while deep strategy compares the equality from all depth levels.

So, which one should I choose?

Well… it depends on your use case! The most important thing is for you to really understand the problem you’re solving with your code and the trades-off of each approach.

Talking about trade-off

Let’s enumerate some pros & cons of each approach:

┌────────────────────┬─────────┬──────┐
│ │ Shallow │ Deep │
├────────────────────┼─────────┼──────┤
│ Fast Performance │ ✔ │ ✖ │
│ Order Matter │ ✖ │ ✔ │
│ Reference Equality │ ✔ │ ✖ │
│ Strict │ ✔ │ ✔ │
└────────────────────┴─────────┴──────┘

Dependency

We will be using an improved version of the JavaScript typeof() operator, which we covered here before, if you haven’t read it yet, click in the link bellow and check that out!

Formulas

Shallow Comparison

Deep Comparison

Got something on your mind? Let us know in the comments 💪

--

--

Marcos Gonçalves
NERDJACKING

Lead Engineer | Architect | Developer Advocate | 12+ years of experience. Also a lover of a good beer in his spare time.