+ 4

Var++ is NOT Var+=1 (JS)

Nobody ever told me this, so today I just lost a lot of time searching for an hidden bug, to sum it I made an example: var num1 = "1"; var num2 = "1"; num1++; num2+=1; console.log("num1 ++ : "+num1); // console returns 2 console.log("num2 +=1 : "+num2); // console returns 11 The same behaviour applies also whenever you increment properties, in my case a canvas fillRect position which had as coordinates imput values. Summary: If Var in "Var++" is recognised as a string type, the ++ silently converts it into a number type then adds 1, while the "+=1" encountering a var of string type (even if it is a number without any chars) will operate a concatenation. Hope I helped anyone, and sorry if you already knew it. Try it= https://code.sololearn.com/W9W29a2GGrqW/#js

19th Mar 2018, 7:15 PM
Andrea Santona
Andrea Santona - avatar
2 Respostas
+ 3
That is so because the unary ++ operator works only with integers, while the binary += operator works with both strings and numbers. When it deals with a number, it simply adds. But when it encounters a string, it does not add but concatenate the string and the number converted into a string. But during the first case, it added the number to the string converted into a number.
9th May 2018, 12:22 PM
Naveen Maurya
Naveen Maurya - avatar
+ 2
@saantonandre if you start the variable as a number it will work the same. When you declared the variable you set it to string with quotes. Have fun programming! And good luck bud! var num1 = 1; var num2 = 1; num1++; num2+=1; console.log("num1 ++ : "+num1); // console returns 2 console.log("num2 +=1 : "+num2); // console returns 2
21st Mar 2018, 3:20 AM
Jason Lee
Jason Lee - avatar