A simple example of type coercion is changing a number to a string.
If and when type coercion occurs varies depending on the code being run. It can even happen automatically, so you may have come across it, even without realising.
For example when running a loose equality comparison (==):
As this a loose comparison (==), type coercion occurs and the test will pass. This is because when performing a loose comparison, type coercion occurs on one of the operands, converting it to an equivalent value of the other operand type. For example, converting the number 5 to a string would result in a match.
If this was a strict comparison (===), type coercion would not occur and the operands would not match as their types are not equivalent, which would result in a failed comparison.
A loose comparison can also be referred to as an abstract or double equals comparison and a strict comparison can also be referred to as identity or triple equals comparison.
Implicit vs explicit
When type coercion happens automatically, like in the above example, this is called an implicit type coercion.
Understanding type coercion can be a vital part of understanding how a program will run. Check out the further content links below for more information on type coercion.
- Type conversion
- Type casting
- Type juggling