- Coercion is when a conversion from one type to another occurs.
You can use Boolean, Number and String as:
Constructor functions (Bad)
If we use them with the
new keyword then we will always return an object - not what we expected:
This is a very confusing thing to do in your programs. All 3 are regular objects with prototypes and methods. Don’t use
Factory functions (Good)
When we use them as a factory function they will return the expected type value.
This is really useful to perform an explicit type conversion:
Often we see
!!someVar as a way to get the boolean value of
someVar, don't use
Boolean() instead, is more clear and declarative:
What we learned:
- Boolean, Number and String are functions and we want to use them as factory functions
- As factory function they coerce values to the desired type
- They help us to make our code more clear, declarative and functional
This post was originally published on Nov 8, 2016 in my github.