In programming, type conversion is the process of converting data of one type to another. For example: converting Number data to String.
There are two types of type conversion in JavaScript.
1) Implicit Conversion - automatic type conversion
2) Explicit Conversion - manual type conversion
1) JavaScript Implicit Conversion
In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.
Example 1: Implicit Conversion to String
let result;
result = '5' + 2;
console.log(result) // output : "52"
result = '5' + true;
console.log(result); // output : "5true"
result = '5' + undefined;
console.log(result); // output :"5undefined"
result = '5' + null;
console.log(result); // output : "5null"
Example 2: Implicit Conversion to Number
let result;
result = '5' - '2';
console.log(result); // output : 3
result = '5' - 2;
console.log(result); // output : 3
result = '5' * 2;
console.log(result); // output : 10
result = '5' / 2;
console.log(result); // output : 2.5
Example 3: Implicit Boolean Conversion to Number
// if boolean is used, true is 1, false is 0
let result;
result = '5' - true;
console.log(result); //output : 4
result = 5 + true;
console.log(result); // output : 6
result = 5 + false;
console.log(result); //output : 5
Example 4: undefined used with number, boolean or null
let result;
result = 5 + undefined;
console.log(result); // output : NaN
result = 5 - undefined;
console.log(result); // output : NaN
result = true + undefined;
console.log(result); // output : NaN
result = null + undefined;
console.log(result); // output : NaN
JavaScript Explicit Conversion
You can also convert one data type to another as per your needs. The type conversion that you do manually is known as explicit type conversion.
1. Convert to Number Explicitly
let result;
// string to number
result = Number('123');
console.log(result); // output : 123
result = Number('624e-1')
console.log(result); // output : 62.4
// boolean to number
result = Number(true);
console.log(result); // output : 1
result = Number(false);
console.log(result); // output : 0
2. Convert to String Explicitly
//number to string
let result;
result = String(123);
console.log(result); // output : "123"
result = String(3 + 5);
console.log(result); // output : "8"
//other data types to string
result = String(null);
console.log(result); // output : "null"
result = String(undefined);
console.log(result); // output : "undefined"