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
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
+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.
! 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 have for many been an annoying affair to understand well. But fear not, the difference between
=== 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