Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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?

share|improve this question
    
One of the most interesting questions I've seen in weeks. And which, like most really good questions, taught me something in the process of answering. – T.J. Crowder Apr 24 at 17:09

1 Answer 1

up vote 5 down vote accepted

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:

  • Let oldValue be ToNumber(GetValue(lhs)).
  • Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).
  • Call PutValue(lhs, newValue).
  • Return oldValue.

Whereas, += is defined quite differently, not coercing to number as an early step, and thus ending up applying string concatenation rather than addition.

share|improve this answer
1  
Thanks.. I was always under the impression that x++ and x += 1 were the same but apparently this is an important difference. – billynoah Apr 24 at 17:03
    
@billynoah: That's a very, very good observation. In most languages with B-like syntax (C, Java, etc.), ++x being essentially x += 1 (not x++, the final value of the expression is different) would be an accurate statement. But not JavaScript, with its loose typing. :-) – T.J. Crowder Apr 24 at 17:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.