How Type Coercion works in JavaScript

Posted by

The JavaScript documentation defines coercion as automatically or implicitly converting one data type to another data type.

Conversion of data formats is a practice that is very common in most applications. For example, converting a word document to a PDF document, converting XML to an excel spreadsheet, and the list is endless.

In programming, we can also be able to convert one data type such as an object into a format that can be transmitted over a network using serialization. Serialization is the process whereby an object is converted into a stream of bytes that can be saved in a database, a file, or memory.

In JavaScript, coercion is prevalent in three data types that include: string, number, and boolean. In this tutorial, we will learn how coercion works in JavaScript, the common coercion pitfall when using the == operator and how to avoid it, and the difference between coercion and conversion.

Coercion in string data type

In string coercion, any addition of a string with another data type always returns a string.

We will use the webStorm development environment to test all the examples in this article. Open the application and press File > New > Project. On the window that opens, select Node.js, and enter the project name as coercion instead of untitled. Press the button labeled Create to create a new node project.

Create a file named string-coercion.js, and copy and paste the following code into the file.

function stringCoercion(){
    console.log("10" + 10);
    console.log("10" + "10")
    console.log("10" + 10);
    console.log("10" + undefined);
    console.log("10" + null);
    console.log("10" + NaN)
}

stringCoercion();

Note that the + operator in the context of a string is used to indicate a concatenation operation. String concatenation is the process whereby a string is appended to the end of another string to form a new string.

Since the first operand the log() method is a string followed by the + operator, coercion to string is done on all the data types as shown below. Run the above code using the following command.

 node string-coercion.js 

output:

1010
1010
true10
10undefined
10null
10NaN

Common coercion pitfall

Copy and paste the following code after the stringCoercion() method.

function comparisonAndStringCoercion(){
    const  requestParam = "20";
    const  localValue = 20
    const result = requestParam == localValue;
    console.log(result)

    const correctResult = requestParam === localValue;
    console.log(correctResult);

}
comparisonAndStringCoercion();

When developing web applications, we often read request parameters from an HTTP request so that we can make some decisions or computations.

A framework such as Angular reads request parameters as a string by default, and if we are not aware of this we can have bugs in our applications.

For example, if we read the request parameter "20" and compare it using the == operator with a local variable 20, the result will evaluate as true.

As you have noted, we are comparing a string with a number, and the local variable which is a number gets coerced to a string thus the result evaluates to true.

The result of the comparison should evaluate as false since we are comparing two different data types. To prevent this, we should use the triple equals operator === instead of the == operator.

The triple equals === evaluates to false for values that are not of the same type and this means that the comparison is strict for all the data types.

Run the above code and observe the result of the operation with coercion and the result of the operation without coercion as shown below.

true
false

Coercion in number data type

When working with numeric values, we can leverage the following mathematical operators: subtraction -, multiplication *, division /, and modulus %.

The only operation that we should avoid when using numeric values with strings is the addition + operator.

Create a file named number-coercion.js under the root folder and copy and paste the following code into the file.

function numberCoercion(){
    console.log(20 * 20);
    console.log(20 / "5");
    console.log(20 % "5");
    console.log(20 - "10");
    console.log("20" * "6");
     console.log(20 * "john");
    console.log("john" - "doe");
}
numberCoercion();

The three operators mentioned above always return a number when a first operand is a number and the second operand is a numeric string.

The second operand should be numeric of type string for the coercion to work, otherwise, the result is NaN which means the value is not a number.

If the two operands are of type string but do not contain numeric values the result evaluates to NaN.

Run the above code using the following command.

node number-coercion.js 

output:

400
4
0
10
120
NaN
NaN

Coercion in boolean data type

In computer science, logic gates represent a boolean value of true with the value 1 and a boolean value of false with the value 0.

In JavaScript, the boolean values true and false are coerced to the numeric values 1 and 0 respectively.

Create a file named boolean-coersion.js under the root folder and copy and paste the following code into the file.

function booleanCoercion(){
    console.log(true * 20);
    console.log(false * 20);
    console.log(false / null);
    console.log(true + NaN);
    console.log(false - undefined);
}
booleanCoercion();

The result of a boolean operation with a type that is not a number evaluates to NaN, and the result of a boolean operation with a number returns a number.

Run the above example, and observe that the first line of the log() method returns 20 because true is coerced to 1 leading to the operation 1 * 20.

The second line returns 0 because false is coerced to 0 leading to the operation 0 * 20. Use the following command to run the above code.

node boolean-coercion.js 

output:

20
0
NaN
NaN
NaN

Difference between coercion and conversion

Conversion is a term that is often confused with coercion, but they are used to achieve the same objective.

The difference between coercion and conversion is that conversion is done explicitly by the developer while coercion is done implicitly at runtime.

Conversion can be achieved by either, invoking a method of a type that defines how to convert that type to another type, or invoking the constructor of a type, and passing the argument to be converted to another type to the constructor.

Converting a type to a string

Create a file named named string-conversion.js under the root folder and copy and paste the following code into the file.

function stringConversion(){
    const price = 50;
    console.log(typeof price)

    let numericString = price.toString();
    console.log(typeof numericString)

    let numericStringTwo = String(price);
    console.log(typeof numericStringTwo)

}
stringConversion();

In this code, we are converting a value of a type number to a numeric string by using the toString() method and the String() constructor.

To verify that the two approaches convert the number to a numeric string, we use the typeof keyword to check the type of value returned. Note that there are other methods apart from the toString() method that you can use to convert a type to a string.

Run the above code and observe that the value returned is a type string. Use the following command to run the file.

node string-conversion.js 

output:

number
string
string

Converting a type to a number

Create a file named number-conversion.js under the root folder and copy and paste the following code into the file.

function numberConversion(){
    const numericString = "100";
    console.log(typeof  numericString);

    let numeralOne = parseInt(numericString);
    console.log(typeof numeralOne);

    let numeralTwo = Number(numericString);
    console.log(typeof  numeralTwo);
}
numberConversion();

In this code, we have converted a numeric value of type string to a value of type number using the parseInt() method and the Number() constructor.

To verify that the numeric string was converted to a number, we use the typeof keyword to check the type of value returned.

Run the above code using the following command and note that the two approaches return a value of type number as shown below.

 node number-conversion.js 

output:

string
number
number

Converting a type to a boolean

Create a file named boolean-conversion.js under the root folder and copy and paste the following code into the file.

function booleanConversion(){
    let boolean0ne = Boolean("true");
    console.log(typeof  boolean0ne);

    let booleanTwo = Boolean(0);
    console.log(typeof  booleanTwo);

    let booleanThree = Boolean(1);
    console.log(typeof booleanThree);
}
booleanConversion();

The Boolean() constructor converts the type passed as the argument to a boolean. Use the typeof command to verify the type returned as we have done in the previous examples.

Run the above code and verify that the data types passed to the constructor are converted to boolean values as shown below.

node boolean-conversion.js 

output:

boolean
boolean
boolean

Conclusion

In this tutorial, we have learned how coercion works in JavaScript. This was the main topic of the article. Next, we learned how to use the strict equality operator === to prevent type coercion, and finally covered the difference between coercion and conversion with an example.

Leave a Reply

Your email address will not be published. Required fields are marked *