Type Conversions in JavaScript
Image By: morioh.com
In Javascript, when we try to convert one type to the other, In some cases the conversion is done implicitly/ automatically and in some scenarios, you have to explicitly convert one type to the other.
If you have basic knowledge of JavaScript, you must have noticed that any value that is passed to the "alert()" method in the JavaScript gets converted to the String. This is implicit conversion.
But in some cases, you have to explicitly convert a value to the expected data type.
String Conversion
String() function is used to convert a value to the string type. Note that earlier value was the boolean field but Using function we can change its type.
You can use the toString() function as well to convert a value to the String type.
Numeric conversion
we can use the Number() function to convert a value to the number. Below is an example of converting string value to the number.
In the above example, Number() function converted the String value to the number. But if the string is non-numeric then Number() will return NaN (Not a number) and If the string is empty, Number() function will return 0.
Convert a boolean value to the Number type:
Boolean Conversion
The values like null, undefined, and NaN returns false in Boolean conversion and other value returns true.
0 Comments