0

When we perform sum operation between two elements, it needs to be converted into a number, without converting it merges them because element.val() returns a string. But when we perform other operations like multiply, subtraction or divide it gives the expected result without performing any typecast.

function add() 
{
   alert($("#first").val() + $("#second").val());
}
function divide() 
{   
    alert($("#first").val() / $("#second").val());
}
function multi() 
{ 
   alert($("#first").val() * $("#second").val());
}
function subst() 
{  
    alert($("#first").val() - $("#second").val());
}
<input type="text" Id="first" />
<input type="text" Id="second" />
<input type="button" Id="add" onclick="add()" value="+"/>
<input type="button" Id="divide" onclick="divide()" value="/"/>
<input type="button" Id="multi" onclick="multi()" value="*" />
<input type="button" Id="subst" onclick="subst()" value="-"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  • have a look at http://stackoverflow.com/q/13953939/6868584 – Aidin Feb 08 '17 at 11:59
  • Possible duplicate of [How to force JS to do math instead of putting two strings together](http://stackoverflow.com/questions/4841373/how-to-force-js-to-do-math-instead-of-putting-two-strings-together) – Stephan Bauer Feb 08 '17 at 12:14
  • here some use cases and [explanations](http://www.java2s.com/Tutorials/Javascript/Tutorial/0110__Javascript_arithmetic_operators.htm) – Chandan Rai Feb 08 '17 at 12:17

1 Answers1

6

+ operator is used either for concatenating strings or for adding numbers (the interpretter will favor the concatenation if one of the operands is a string). But /, * and % are used only with numbers so the interpretter is forced to see the operands as numbers.

For more explanation, here is an answer I gave about two days ago for a similar question. (It's pretty long so I won't repost it here again).

Community
  • 1
  • 1
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73