Have you ever wondered what the real difference is between == and === ?
Coercion
Typecasting. Converting. Coercion. We tend to have many names for the things we love. Coercion in JavaScript is really just about converting one value to another. For example, 5 + ''
will convert the number 5 to a string. If we assign this expression to a variable (or wrap the expression in parentheses), we will suddenly have available methods from the string prototype. For example, we can retrieve the field .length
.
This is an example of implicit type coercion - we do not explicitly write out that we want to convert to a string. All lines below are examples of explicit type coercion to numbers:
Number(false); // 0
Number(""); // 0
Number([]); // 0
Number(null); // 0
However, JavaScript also has more subtle ways of coercion:
+new Date(); // 15397079399379
Here, the plus sign indicates trying to retrieve the number value representation of the Date
object. Read more about this fun and a tad confusing unary operator in Kristofer's article from earlier this fall.
My favourite way of do explicit coercion in JavaScript is with !
:
if(!person.age)
The !
is actually coercing the statement to a boolean and turning the sign in the same operation. Hence, we may use the operator to check the truthyness or falsiness of all values in JS: !!foo
. Tada, double negation has never been more fun! 🎉
Or, you can go for the exam way of understanding truthyness/falsiness by memorizing the following list of all falsy values in JS (the rest are truthy):
undefined;
null;
false;
0 - 0;
NaN;
("");
Equality checks
Equality checks have for many been an annoying affair to understand well. But fear not, the difference between ==
and ===
is best explained by JS evangelist Kyle Simpson:
The correct description is: "== allows coercion in the equality comparison and === disallows coercion."
With this rule of thumb in mind, the following results should be expected:
var a = 5;
var b = "5";
a === b; // false
a == b; // true