JavaScript Type Conversion

Like other programming languages javascript also allows to convert the types of values. For example.

1. Strings to Numbers
2. Numbers to Strings
3. Dates to Numbers
4. Numbers to Dates
5. Booleans to Numbers
6. Numbers to Booleans

Converting Strings to Numbers

In this example global mehtod Number() is used to convert string to number.
Strings containing numbers (like "3.14") convert to numbers (like 3.14).
Empty strings convert to 0.

<script type = "text/javascript">
Number("3.14")    // returns 3.14
Number(" ")       // returns 0
Number("")        // returns 0
Number("99 88")   // returns NaN
</script>                  
        

Converting Numbers to Strings

In this example global method String() is used to covert number to string.
It can be used on any type of numbers, literals, variables, or expressions:

<script type = "text/javascript">
String(x)         // returns a string from a number variable x
String(123)       // returns a string from a number literal 123
String(100 + 23)  // returns a string from a number from an expression
</script>                  
        

Example of type casting

Following is the code for type casting in JavaScript −


<h4>Type casting in JavaScript.</h4>
<div class="sample">44</div>
<div style="color: green;" class="result"></div>
<button class="Btn btn-primary p-1">CLICK HERE</button>
<h5>Click on the above button to convert it into string,number and boolean.</h5>
<script>
   let sampleEle = document.querySelector('.sample');
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML += 'String = '+ (String(sampleEle.innerHTML)+22) + '<br>';
      resEle.innerHTML += 'Number = ' + (Number(sampleEle.innerHTML)+22) + '<br>';
      resEle.innerHTML += 'Boolean = ' + Boolean(sampleEle.innerHTML) + '<br>';
   });

</script>                  
        

Output of above code

Type casting in JavaScript.

44
Click on the above button to convert it into string,number and boolean.








The Best

Comment here

If you have any query, if you want to know something about any of technical course related to computer science field, if you have any suggestion about relevant to uploaded content or if you anything wrong here (any mistake in content) than please contact us. Keep in mind, comment should be according to community guidelines.