JavaScript automatically identify the type of data and convert it accordingly. For example, if we write any value in quotes (''), it will be treated as string, but if division, multiplication, subtraction is performed then, JavaScript engine automatically convert it into number and perform mathematical action on it. Similarly, if we display an value in alert box, it will automatically be converted into string.
The three most widely used type conversions are string, number, and boolean. Let's understands them, how to convert one data type into another.
Example 1: String to Number automatic type conversion.
console.log('10'*'10') //100 automatically converted to number,
Similarly it will automatically converted for division '/' and subtraction '-'
console.log('10'+'10') //1010 does not automatically converted to number, '+' is use to concatenate strings.
To explicitly convert a data type into number, use Number() function.
let a='10'; //String data type let b='20'; //String data type let c=Number(a) + Number(b); //Output: 30
When you input a value from user via prompt box, textbox or any other HTML form element, then, make sure to use explicitly conversion into the proper data type. Default data type of textbox is string.
let a='some value'; //String data type let b=Number(a); //Output: NaN, because it is not a proper number
let a=true; //Boolean data type let b=false; //Boolean data type let c=Number(a); //1 let d=Number(b); //0
To convert any other data type into string, use String() function.
let a=10; //Number data type let b=20; //Number data type let c=String(a) + String(b); console.log(c); //Output: 1020
Boolean function will convert value into true or false. Values like 0, empty string, null, undefined, and NaN, become false, all other values are true.
console.log(Boolean(1)); //true console.log(Boolean(0)); //false console.log(Boolean(5)); //true console.log(Boolean('text')); //true console.log(Boolean('')); //false
Ad: