0
I can’t understand this JS arithmetic - Seems like a simple minus but the result is unexpected
Can someone please explain to me this? I can’t figure it out: var c = 10 + "3"; var d = 3 + "4"; // ans = 69 var k = 5 + "6"; var l = 10 + "2"; // ans2= -46 var ans = c - d; var ans2 = k-l; ?? What is going on here?
5 Respuestas
+ 6
// 1st
c = 10 + "3" = '103'
d = 3 + '4' = '34'
c - d = '103' - '34' = 69
// 2nd
k = 5 + '6' = '56'
l = 10 + '2' = '102'
k - l = '56' - '102' = -46
In simple words Javascript concatenated string and number then implicitly converted string to number when performing arithmetic operations between them.
http://2ality.com/2013/04/quirk-implicit-conversion.html
+ 3
x = 7 + '2' = '72'
y = 4 - '8' = -4 // minus operator operates on numbers only so 8 is implicitly converted to number 8
= x - y
= 72 - -4
// subtract operation works with numbers only
=72 + 4 = 76
//Minus times minus is plus.
x - -y = x + y
#read the below resource for info about minus operator
https://mathlesstraveled.com/2009/09/29/minus-times-minus-is-plus/
+ 1
Oh my gosh Thank you!! The code you wrote to explain says it all... really helpful. Wow!!
+ 1
I've encountered another problem. Please can you explain how this works then?
It does not follow the logic you described above.
As above the answer should be 24, but it is 7:
var x = 7 + "2";
var y = 4 - "8";
alert(x-y);
//76
+ 1
Thank you for answering. That was far more complicated than I expected... but you explained it very well. That the minus operator implicitly converts a string to numbers is something I didn’t learn through the course!