Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

How to differentiate Addition Operator with Concatenation Operator in Javascript

All we know about Concatenation operator (+) in JavaScript which combine two string with “+” operator in java Script(If you want to do concatenation in PHP than use “.” character between two strings). Problem creates when you want to do addition of two JavaScript variables.

JavaScript is a client side scripting language in developing web application , same as other language you can do logical operation in JavaScript such as summation , subtraction etc. When you need to add two form element values and assigned in to other form element using JavaScript , some developer will face the situation that instead of addition it will do concatenation operation and give result which combine two variables.

var a;
var b;
var c;
a = document.getElementById(‘id1’).value;
b = document.getElementById(‘id2’).value;
c = a + b;

In the above code if value of a is 2 and value of b is 3 than you will get 23 as a result in variable c instead of 5 as you expected. Its because what you are getting in variable a and variable b are not numbers even through the looks like numbers. They are the strings and you need to convert them in to numbers before doing addition using “+” operator.

Look at below for the solutions.

var a;
var b;
var c;
a = document.getElementById(‘id1’).value;
b = document.getElementById(‘id2’).value;
c = Number(a) + Number(b); OR c = parseInt(a) + parseInt(b);

Number() and parseInt() will convert string in to numbers.

To know more about programming,JavaScript issues,jQuery,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.

Enter your email address:
Feel free to ask any question. Just leave your comment below and we will answer your comment with in 24 hours.
Share:

1 Comment

Leave a Reply

Your email address will not be published.