var fir=prompt("Enter first Number");
var sec=prompt("Enter second number");
var sum=Number(fir)+Number(sec);
alert("The sum is " + sum);
alert("The difference is " + fir-sec);
alert("The product is " + fir*sec);
alert("The division is " + fir/sec);
Now: suppose fir=2 and sec=1.
The output is:
3
NaN
2
2
Why is the difference NaN
instead of 1?
*
and /
have higher operator precedence than +
and -
, just like with PEMDAS order of operations in standard math. Specifically, +
and -
have precedence 13, whereas *
and /
have precedence 14.
When an expression has +
and -
s only, they're evaluated in left-to-right order. So, your code is equivalent to:
alert(("The Difference is " + fir) - sec);
alert("The product is " + (fir*sec));
alert("The division is " + (fir/sec));
In the second and third alert
, fir
and sec
get combined into a single numeric expression before being concatenated with the prior string.
In the first alert
, "The Difference is " + fir
get put together first, resulting in another string (a string +
a number results in another string). So then you have
alert((someString) - sec);
But someString - sec
doesn't make sense - you can't subtract something from a string, so the expression resolves to NaN
.
You can do one thing
var fir=prompt("ENter 1st Number");
var sec=prompt("Enter second number");
var sum=Number(fir)+Number(sec);
var sub=Number(fir)-Number(sec);
alert("The Sum is " + sum);
alert("The Difference is " + sub);
alert("The product is " + fir*sec);
alert("The division is " + fir/sec);
Usually, the plus operator + sums numbers.
But, if the binary + is applied to strings, it merges (concatenates) them:
let s = "my" + "string"; alert(s); // mystring Note that if one of the operands is a string, the other one is converted to a string too.
For example:
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
See, it doesn’t matter whether the first operand is a string or the second one. The rule is simple: if either operand is a string, the other one is converted into a string as well.
However, note that operations run from left to right. If there are two numbers followed by a string, the numbers will be added before being converted to a string:
alert(2 + 2 + '1' ); // "41" and not "221"
String concatenation and conversion is a special feature of the binary plus +. Other arithmetic operators work only with numbers and always convert their operands to numbers.
For instance, subtraction and division:
alert( 2 - '1' ); // 1
alert( '6' / '2' ); // 3
reference https://javascript.info/operators
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With