Explaining the inexplicable: ‘===’ != ‘==’
The ambiguity continues…
You open your View Controller, jump to that method definition and bam: you have found the vile line.
The clock ticks away to glory while you scratch your head, tear off your hair, drink Red Bull (no, contrary to the vox populi, I am not advertising Red Bull) in frustration; nothing. “WHY ME, GOD!!?!” And then you realise and have that ahaa moment. Suddenly, everything makes sense. What was it? What did it do? … To be continued
Now the story above sounds like a classic Spielberg thriller, except it’s not. It’s my poor attempt to make this monotonous thing a little more interesting. Yeah, my sense of humour is amazing. What we have in store for today’s article is the triple-equal-to vs. the double (or classic) equal to.
Let’s have a look at the code I referred to in my (failed) suspense movie:
I tried to re-create the error and I noticed a pattern: it only happened when the ajaxObject had the status_code set to 200; or when the response was alright (alas).
Hmm… That’s weird! I logged the ajaxObject of the 200 response to get this:
And when the status code was 400, this was the response:
“Ahhh!!! How did I miss this?”
Now, the first thing you notice, right off the console (because we aren’t cricketers) is that 400 is a number while “200” is a string.
So, theoretically, the runtime with the made a type comparison as well as a value comparison and it only executed the if only if the type and the value, both were the same. The fix was simple, I changed it to the double “=” to make it check only for the value.
This brings us to the crux of this article: what is the difference between “===” and “==”.
Imagine we have the following bit of code and we want to compare if ‘a’ is equal to ‘b’; not the type, but only the value.
We can simple do:
Now we see that the “==” operator checks for the value of the two variables, regardless of the type of the variables. So, you can be checking a string to a number.
What if you wanted to check both: the type as well as the value. Simple, you use the “===” operator.
You can imagine the “===” operator decomposed to the following function:
Simple, eh? Yeah! That’s it.
So remember, use the “===” operator when you want to check the type and the value (useful for checking API responses) and use the “==” operator when you just care for the value.
Something very basic and fundamental, but often breaks the code. So, read (and think) before you ship. This reminds me of a poem: O Captain! My captain! But that’s the topic for another post. ;)