In this post, we will be learning about how to convert JavaScript variables into different types.
In JavaScript, you can convert variables into different types using specific functions.
JavaScript has built-in functions that can be used to change a variable’s data type.
Such functions include number()
, string()
and boolean()
.
How To Determine The Datatype
You can use the keyword typeof
(no bracket) to determine the datatype of a particular variable.
Typeof
is an operator; it is not a variable itself.
JavaScript Code
typeof "twrewrew"
Conversions Variables can be converted to a new variable type in data type by using a built-in function.
Converting Numbers To String
To turn a number into a string, you can create it as a string object with ""
around the number.
JavaScript Code
String(111)
String(100+11)
In addition, every number value comes with a built-in method called toString() that can change its type to string.
JavaScript Code
x.toString()
(111).toString()
(100 + 11).toString()
Converting Boolean to String
We can use the String()
method on a boolean variable to convert it into a string.
This will yield a string of either false or true.
String(false)
String(true)
Converting Dates To Strings You can convert dates into strings using String() or getDate().
JavaScript Code
d = new Date();
String(d);
JavaScript Code
d = new Date();
d.getDate();
Converting String To Number
You can also use the number()
method to turn a string into a number, so long as the string is numerical.
However, this only works if the string is actually a number (e.g. "1245") to begin with. When using the number()
function, every other string will convert to NaN.
JavaScript Code
Number(123)
Number("");
Number(" ");
Number("44 55 66");