What is Type Conversion
Explicit type conversion, also known as type casting, is performed using built-in functions such as Number(), String(), and Boolean(). These functions allow you to explicitly convert a value from one type to another. For example, you can use the Number() function to convert a string containing a number to an actual number data type.
Converting Values to Strings:
Below code is going to convert the number to a string, boolean value to a string and dates to a string.
Converting Values to Numbers:
Below code converts a numerical text, dates and boolean values to a number.
If the string is a non-number then it converts it to NaN and strings of white spaces or empty strings will convert to 0.
I hope this helps you better understand type conversion and it's use. This is just the beginning of type conversion. Try to answer these 5 questions on what we just discussed.
var myString = '123'; var myNumber = Number(myString);
var myNumber = 123; var myString = String(myNumber);
var myString = '123'; var myNumber = parseInt(myString, 10);
var myString = '3.14'; var myNumber = parseFloat(myString);
var myNumber = 123; var myString = myNumber.toString();
Top comments (0)