Coercing with Boolean, Number and String objects in JavaScript

Photo by funnyjunk.com

Today we are going to talk about these 3 global Objects (functions) in JavaScript and how to use them as factory functions to coerce different values.

Important:

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 new.

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 !!, 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

Read more:

This post was originally published on Nov 8, 2016 in my github.