Type coercion or type conversion in javaScript

Type Conversion

Type coercion or Type Conversion is the way by which we can convert one type of primitive data type to another primitive data type. As we discuss in the data type article we have discussed that we have two types of data types first one is the primitive and the second one is none primitive type. Primitive data are two types first one is number, string and boolean. Usually, all three are different to each author but sometimes we are in trouble due to data. Let us take an example to suppose that you are invoking API and API giving some ids in the form of a number (like 1, 2, 3) and you have fixed for that now after some time requirement is changed and now you are getting ids in the form for string (Like “1”, “2”) but you have a fix for number so in that case, your code can crash so we need to handle both cases.

But before we going further we need to understand some basics about type coercion.


  var num = "123"; // String value but in form of number

and we want to add this value with another number like 120.


  var num = "123";
  console.log(num + 120);
  // Expected 243 but we are getting 123120

So we need to be careful when we are dealing with this kind of situation.


  var num = +"123";
  // or var num = new Number("123");
  console.log(num + 120);  // 243

Here we are using + unary operator or Number constructor to convert the string value of a number.

I hope you understand the concept now we can take another example. Here we have 3 primitive values and we are converting those values to another datatype values.


  var str = "", str_num = "2", num = 2;

  // Boolean value
  console.log(Boolean(str)); // false
  console.log(Boolean(str_num)); // true
  console.log(Boolean(num)) // true

  // Number value
  console.log(Number(str)); // 0
  console.log(Number(str_num), " and ", +str_num); // 2
  console.log(num;) // 2

  // String value
  console.log(String(str)); // ""
  console.log(String(str_num), " and ", (str_num + "")); // "2" and "2"
  console.log(String(num)); // "2"

You May Also Like

About the Author: Pankaj Bisht