Javascript type coercion and typecasting

 Javascript type coercion and typecasting

Type coercion is the automation or implicit conversion of values from one data type to another. 
We've already seen the effect of type coercion in equality operators post.

In this post we are comparing it with type conversion.

Type conversion or typecasting is used to transfer data from one data type to another.

Let's look at an example. The first function call in the button is implicit conversion.
However, in the second function call for the other button, we are passing a string 0x11 and explicitly saying, hey Javascript, convert this string to a number before addition thus we use Number("0x11");

<!DOCTYPE html>

<button onclick="add(52.0)">Add 5 and 2.0</button>
<button onclick='add(5Number("0x11"))'>Add 5 and string 0x11</button>
<p id="result"></p>

function add(num1num2) {
    var x = document.getElementById("result");
        x.innerHTML = num1 + num2;


Post a Comment