Javascript numbers concatenating instead of adding

Created at 08-Jun-2020 , By samar

This is one of the common issue found when we try to add two number in javascript.  Before we understand about the issue why it happens first we should know the  javascript variable types where the value actually stored. JavaScript is a loosely typed language, means you don't have to specify what type of information will be stored in a variable in advance. Now Lets understand about the issues why it happens when we try to add these numbers its concatenated instead of adding. 

There we are using two different method and  try to add two numbers in javascript . 

//method 1
var str = "Display sum of two digit = ";
var str = str + 2 + 2;
alert(str);


//method 2
var z = 2 + 2 ;
alert(z);

Method 1 :

Here we try to add two numbers in javascript and display with a string using concatenate method. Instead of adding numbers,  values are treated as a sting and concatenate with the string 'Display sum of two digit ='  and output display as :

Display sum of two digit = 22

Method 2 :

Here in method 2 we add two number and alert the output and output display as :

4

Method 2 display the desirable ouput but what with the first method when we try to display number with string using concatenate method . There is a solution we easily can add these number using brackets . This method first add these two values and concatenated to string.

 var str = "Display sum of two digit = ";
 var str = str + (2 + 2);
 alert(str);

//output : Display sum of two digit = 4 

 

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.