Why does increment using ++ work with strings in javascript?
Usually, when I get the value of a form input using jQuery, I have to convert it to a number before doing any math. For example, using the unary plus operator to convert and then increment:
var x = +$(this).val();
x += 1;
But for some reason it ++
works with strings and does the conversion automatically:
var x = $(this).val();
x++;
Why? Is it always safe?
source to share
It works like this because the first thing any of the increment operators do is coerce its operand to a number, which is in Β§11.3.1 of the spec . And being in the spec, yes, it is something you can rely on.
Skipping some spectra, algorithm:
- Let
oldValue
beToNumber(GetValue(lhs))
. - Let
newValue
be the result of adding a value1
tooldValue
, using the same rules as for the operator+
(see 11.6.3). - Challenge
PutValue(lhs, newValue)
. - Return
oldValue
.
While +=
defined in a very different way , it does not force the number as an early step, and thus ending up applying string concatenation rather than appending.
source to share