Type conversion in JS
Type conversion in any language is simply changing the datatype of one variable to another required datatype.
Type conversion in Java script is simple yet confusing. We can convert data types by using these basic methods :
Number () : converts a variable’s datatype into a number.
String() : converts a variable’s datatype into a string.
Boolean() : converts a variable’s datatype into Boolean value.
Above code snippets show the usage of the methods mentioned above.
The problem occurs when we try to attempt conversion of incorrect values. For example when we try to convert a string which not only has number but also some characters along with it.
Let’s see with an example.
Here we are trying to convert a string with characters to a number. Upon logging the variable ‘number’ we get ‘NaN’ as its value. But when we log the ‘typeof’ the variable ‘number’ we get it is a number.
Similar problems can occur when we try converting other incorrect values.
So, Make sure to give correct values before attempting to convert datatypes in Javascript.
Subscribe to my newsletter
Read articles from Yashas directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by