In this section, we'll look at how type validation is typically handled in JavaScript and how the type-checking functions in Lo-Dash improve the situation.
Type coercion happens in JavaScript when one object is compared to another. That is, we have one object operand, the operator, and the second object operand. Depending on the operation being performed, the second object might be coerced into a representation that is compatible with the first operand. Take the following operation, for example:
true == 1
These are obviously different objects representing different primitive types. In the spirit of loosely typed programming, this expression triggers type coercion. The first operator is a Boolean value and the second operator is a number. The ==
equality operator will take the Boolean representation of 1
and compare it with true
. This is why, this expression always evaluates to true
. The values are roughly equal.