Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
XML
<script language="javascript" type="text/javascript">
var num1="5";
var num2="3";
var sum=num1-num2;
document.write("The sum is:" +sum);
</script>


Addition will give 53 as O/p alright.
subtraction is giving 2 as o/p.Why this o/p is produced.
Want know the reason for that.
Posted

1 solution

Javascript is a weakly typed language, which means it tries to convert data for you when it can.
And it specifically has a string concatenation operator: '+'

So when it parses your code and sees this:
JavaScript
var num1="5";
var num2="3";
var sum=num1+num2;
It looks at the actual datatypes you have given it and because at least one of them is a string it decides to use the string concatenation operator and combines the strings - so you get a string result "53"

But...there is nothing sensible that can be subtracted from strings - so there is no "string deconcatenation" operator. So when it encounters this:
JavaScript
var num1="5";
var num2="3";
var sum=num1-num2;
it has to use the subtract operator, and converts each strign to a number first - so you get 5 - 3, or 2
 
Share this answer
 
Comments
Janardhanam Julapalli 17-Oct-14 2:06am    
Thanks for the explanation.I was thinking that some obvious reason might be there.But it is so simple.
OriginalGriff 17-Oct-14 3:26am    
You're welcome!
[no name] 17-Oct-14 2:15am    
Good one !!
I didnt know this.
Janardhanam Julapalli 17-Oct-14 2:17am    
Anyone think all programmers(may be Javascript) know this answer?
OriginalGriff 17-Oct-14 2:32am    
Probably not: I suspect a lot of them just work on the "then a miracle occurs" approach... :laugh:

I hate weakly typed languages: they always give rise to this kind of fun and games because the compiler / interpreter makes assumptions about what you meant to write!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900