April 23, 2017
When Does Coercion Occur
*Implicit Coercion* var a = 1 var b = "1" a == b // returns true *Explicit Coercion* b = a.toString(); typeof a // number typeof b // string
b to a
number type so that it can compare to
a which is a number. In the explicit example, we are providing the exact steps to coerce a value.
Since explicit coercion is fairly easy to understand and typically intentional, we’ll focus on implicit coercion and the most notorious situation: comparing two values.
Breaking Traditions and Taking Sides
It is a long-standing, popular stance to avoid coercion when comparing values by using the strict equality operator:
==) operator. There is plenty of similar debate in the community as a whole around whether coercion is a feature or a bug.
While it may be a tradition to stick to
== instead of
The difference between
===is usually characterized that
==checks for value equality and
===checks for both value & type equality. However, this is inaccurate. The proper way to characterize them is that
==checks for value equality with coercion allowed, and
===checks for value equality without allowing coercion.
Written by Steve Frost who lives in Minneapolis using technology to make an impact in the community and our environment.Follow on Twitter