Type-Casting aka Coercion in JavaScript. What you have to know.

With this article, I want to quickly and simply explain the most important ways to convert JavaScript from one value type to another. Type casting is most often referred to as coercion. There are two types of coercion: explicit and implicit.

Implicitly coercion

I am personally a great fan of implicit coercion since I think that, most of the time, it simplifies the resulting code and removes unnecessary complexity.

For the beginning, let’s take a look at my favorite implicit operation of coercion for converting a number into a string.

number to string

    var thisIsANumber = 12;
    var thisIsANumberAsString = thisIsANumber + "";
    console.log(thisIsANumberAsString); // prints: "12"

As you can see, the + operator is working as a concatenation operation and not as a numerical plus. It converts the number into a string before concatenating it with the empty string on the right side.

string to number

    var thisIsANumberAsString = "12";
    var thisIsANumber = thisIsANumberAsString - 0;
    console.log(thisIsANumber); // prints: 12

In the previous example, the - operator works only as a numerical operator. For this reason, the string has to be converted into a number before the numerical operation with zero takes place.

You can find the code of the article here.

comments powered by Disqus