Type conversion in Javascript is the process of converting data of one type to another. There are two types of type conversion in Javascript. They are Implicit conversion and explicit conversion.
Some examples of type conversion are converting from String data to Number, Number to String, etc.
In this blog, we are going to look into Type Conversion in Javascript in detail.
What is happening here is that when we try to add a string and number, obviously, addition cannot be done there. So concatenation takes place there. In this situation, Javascript automatically converted the numeric value to a string to let the concatenation happen.
Explicit type conversion
We have come across the point that explicit type conversion in javascript is those conversions that must be done manually. Let us understand what this means through an example.
Imagine we need to convert a boolean value or a numeric value to a string. How can we do this? Let’s see.
Code:
let number='777';
let answer;
// Type conversion from String to number
console.log(number);
console.log(typeof(number));
// Using Number() function to do the conversion
answer = Number(number);
console.log(answer);
console.log(typeof(answer));
You can also try this code with Online Javascript Compiler
Here we have converted the string value to a number using the Number() function. Since we had to do this conversion for our own requirement, we call these explicit type conversions.
String conversion
We do string conversion when we need the string form of a value. We use the String() function to convert a value to a string.
Ans:- The String() global method can convert dates to strings. The method toString() also does the same thing. Use them as String(Date()) and Date().toString() respectively.
2. What is the use of the parseInt() method?
Ans:- The parseInt() method parses a string and returns an integer.
3. What purpose does the toPrecision() method serve?
Ans:- The toPrecision() method returns a string, with a number written with a specified length.
Key Takeaways
Type conversion in Javascript is the process of converting data of one type to another. Two types of type conversion are Implicit conversion and explicit conversion. Implicit conversions mean that the conversion happens automatically. An Explicit conversion means that the conversion has to be done manually by the user. We can use functions like Number(), String(), Boolean() to achieve explicit type conversion in javascript. Don't stop here. Check out our Basics of JavaScript - guided path to practise Javascriptfrom scratch.