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++;

      

http://jsfiddle.net/m4nka9d3/

Why? Is it always safe?

+3


source to share


1 answer


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

    be ToNumber(GetValue(lhs))

    .
  • Let newValue

    be the result of adding a value 1

    to oldValue

    , 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.

+5


source







All Articles