Computer >> Computer tutorials >  >> Programming >> Javascript

What is the importance of '+' operator in type conversion in JavaScript?


'+' operator has many uses including addition, concatenation, and most importantly type conversion. Generally, we use '+' operator for addition and at some times for concatenation. It also has a lot of use in type conversion. It is very easy to convert a string into a number.

Example

<html>
<body>
<script>
   var num = "23";
   int = +num;
   document.write(int);
   document.write("</br>");
   document.write(typeof int);
</script>
</body>
</html>

output

23
number

Not only type-conversion, this operator is also used to convert booleans to numbers. It changes the boolean values such as true or false to 1 and 0 respectively.

Example

<html>
<body>
<script>
   document.write(+true);
   document.write("</br>");
   document.write(+false);
</script>
</body>
</html>

output

1
0