DEV Community

Cover image for Type Conversion and Coersion in JavaScript

Posted on

Type Conversion and Coersion in JavaScript

Type conversion in javascript:

type conversion

JavaScript variables can be converted to a new variable and another data type either by the use of a JavaScript function
or automatically by JavaScript itself

javascript type conversions are possible only in the following combinations:

  1. number to string

2.string to number

  1. boolean conversions

the conversions to undefined or null type is not possible in javascript


1.conversion of string to Number datatype in javascript

const inputYear = '1991';



2.conversion of string to number is not possible in the following caseas it would yield an reference error.


  1. Not an number(NaN is also a number type in javascript)

console.log(typeof NaN);

//conversion of integer to string


type coersion in javascript

Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.

In case the behavior of the implicit conversion is not sure, the constructors of a data type can be used to convert any value to that datatype, like the Number(), String() or Boolean() constructor.


console.log(i am + 23 + years old);

// the 23 is converted to the string type


//this will result in a string 23102


//this will convert all the strings to Number datatype

let n=1+1;



//the first thing is 11 as a string the n=n-1 will convert all of it to numbers and the result will be 10

Discussion (0)