How to add a string and a number without get concatenated in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

When a string and a number are added then instead of addition, concatenation takes place. They both ended up attaching each other. But if we need to add them we need to convert the string into an integer. In this situation, '+' operator comes into the picture. It actually, converts the string into integer and helps to add them.

Example-1

In the following example, the string is directly added to the number without any conversion. Therefore concatenation takes place instead of addition as shown in the output.

Live Demo

<html>
<body>
<script>
   const string = "100";
   const number = 5;
   document.write(string + number);
</script>
</body>
</html>

Output

1005

Example-2

In the following example, '+' operator is used to convert the string into the number. So, instead of concatenation, the addition took place and the result is displayed in the output.

Live Demo

<html>
<body>
<script>
   const string = "100";
   const number = 5;
   document.write(+string + number);
</script>
</body>
</html>

Output

105

Example-3

In the following example, parseInt is used to convert the string into the number. It does the same operation as '+' operator

Live Demo

<html>
<body>
<script>
   const string = "100";
   const number = 5;
   document.write(parseInt(string) + number);
</script>
</body>
</html>

Output

105
raja
Published on 30-Jul-2019 11:59:47
Advertisements