JavaScript — Type Conversion
Type conversion is the process of converting data of one type to another. For example:-
1. Convert Strings to Numbers
2. Convert Numbers to Strings
3. Convert Strings to Decimals
4. Covert Numbers to Booleans
5. Covert Booleans to Numbers
6. Convert Dates to Numbers
Convert Strings to Numbers
parseInt()
In the following example, we created a string variable called value and assign it to 20. When you use ‘typeof’ we can see it shows as a string on the console.
parseInt() — Convert string to numbers
Unary Plus (+)
Number() method
Convert Number to String
toString() method
String() constructer
Convert Strings to Decimals
parseFloat()
Convert Number to Boolean
Boolean is true or false value.
let value = "2";Get Dinusha Somarathne’s stories in your inbox
Join Medium for free to get updates from this writer.
value = Boolean(value);
console.log(value, typeof value);
If I set this value to ‘0’ then you can see the output as ‘false’. Because zero is a false value. Zero is the only number gives output as false.
let value = 0;
value = Boolean(value);
console.log(value, typeof value);Let’s see what happened if we tried to take a string that is not a number. If I pass this to number.
let value = "Thanks";
value = parseInt(value);
console.log(value, typeof value);We get the value of ‘NaN’. This stands for ‘Not A Number’.
NaN is a property of the global window object. There are other types of operators that can return NaN.
console.log(Math.sqrt(-4));console.log(4 + NaN);console.log(undefined + undefined); - Output - NaNconsole.log("Hi" / 2); - Output - NaNConvert Dates to Numbers
The global method Number() can be used to convert dates to numbers.
convert dates to numbers.
The date method getTime() does the same.







