How to add a number and a string in JavaScript?


In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place.

In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a  number(10). But in case of variable 'b' a string and a number ('5', 5) are added therefore, since a string is involved, we get the result as '55', which is a string. since strings are involved, Variables 'c' and 'd' also return a string as shown in the output.   

Example

Live Demo

<html>
<body>
<script type="text/javascript">
   var a = 5 + 5;
   var b = "5" + 5;
   var c = 5 + 5 + "5" + 5
   var d = "Hello" + 5;
   document.write(a + "<br>" + b + "<br>" + c + "</br>" + d);
   document.write("</br>");
   document.write(typeof(a));
   document.write("</br>");
   document.write(typeof(b));
   document.write("</br>");
   document.write(typeof(c));
   document.write("</br>");
   document.write(typeof(d));
</script>
</body>
</html>

Output

10
55
1055
Hello5
number
string
string
string

Updated on: 29-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements