Is JavaScript a Typed Language?
JavaScript is weakly typed in its nature. This enables us to use implicit type conversion. Take the following for example:
// This will return "12" as 1 will be converted into a string
1 + "2"
typeof (1 + "2") // Will return "string"
// This will return 12 as "12" will be converted into a number
"12" * 1
typeof ("12" * 1) // Will return "number"
Even though we did not specify we wanted to convert the string/number into the other format, JavaScript did it for us implicitly. This is type conversion in action.
So how do you convert different types?
Number
To convert string or any other value to number, use the built-in Number
function:
// Converting data to number
Number('123');
Number(true) // Returns NaN
Alternatively, you can also use parseInt()
, but always make sure you pass the radix as a second parameter. Otherwise, you may happen to get unexpected results. You can also check if something is a number using isInteger
:
Number.isInteger('123'); // returns false
Number.isInteger(123) // returns true
String
To convert data into a string, use the built-in String
function:
String('123'); // returns "123"
String(true); // returns "true"
String(NaN); // returns "NaN"
Boolean
Lastly, if you want to conver something into a boolean, use the built-in Boolean
function.
Boolean(0); // returns false
Boolean(''); // returns false
Boolean(NaN); // returns false
Boolean(1); // returns true
Boolean(123); // returns true
Boolean('true') // returns true
You can also simply double negate a variable to get it converted into a true
/ false
value:
!!0 // returns false
!!1 // returns true
!!NaN // returns false
In summary, you can use these three built in methods to convert different types of data:
Number()
String()
Boolean()
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: