As Which equals operator (== vs ===) should be used in JavaScript comparisons? indicates they are basically identical except '===
' also ensures type equality and hence '==
' might perform type conversion. In Douglas Crockford's JavaScript: The Good Parts, it is advised to always avoid '==
'. However, I'm wondering what the original thought of designing two set of equality operators was.
Have you seen any situation that using '==
' actually is more suitable than using '===
'?
The simple answer is that '==' makes more sense than '===' when you want type coercion to happen during comparisons.
A good example would be numbers being passed in a URL query string. If for instance you have paginated content, and the
page
query parameter holds the current page number, then you could check for the current page withif (page == 1) ...
even thoughpage
is actually"1"
, not1
.I would suggest that there is no problem with using
==
, but to understand when and why to use it (i.e. use===
as a rule, and==
when it serves a purpose). Essentially,==
just gives you shorthand notation - instead of doing something likeIt's much easier to just write
(Or even easier to write)
if (!vble) ...
Of course there are more examples than just looking for "truthy" or "falsey" values.
Really, you just need to understand when and why to use
==
and===
, I don't see any reason why not to use==
where it fits better...Another example is using this shorthand to allow shorthand method calls:
== compares whether the value of the 2 sides are the same or not.
=== compares whether the value and datatype of the 2 sides are the same or not.
Say we have
you can check http://www.jonlee.ca/the-triple-equals-in-php/
Consider a situation when you compare numbers or strings:
but
and
This applies to objects as well as arrays.
So in above cases, you have to make sensible choice whether to use == or ===