Normally when I get the value of a form input with jQuery I am obliged to convert it to a number before performing any mathematical operations. For instance, using the unary plus operator to convert, and then increment:
var x = +$(this).val();
x += 1;
But for some reason ++ works with strings and does the conversion automatically:
var x = $(this).val();
x++;
http://jsfiddle.net/m4nka9d3/
Why? Is this always safe?
It works that way because the first thing either of the increment operators does is coerce its operand to a number, this is in §11.3.1 of the spec. And being in the spec, yes, it's something you can rely on.
Skipping some spectalk, the algorithm is:
oldValue be ToNumber(GetValue(lhs)).newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).PutValue(lhs, newValue).oldValue.Whereas, += is defined quite differently, not coercing to number as an early step, and thus ending up applying string concatenation rather than addition.
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