4

Astonished to find out that a line like this :

$('#TextBox').val(parseInt($('#TextBox').val())++ );

Will not work !

I've done some tests, it plays out to the conclusion that the inline ++ doesn't work (in Javascript as a whole ? Or simply in my example ?).

Here's a test with three pieces of code, it seems that ++ is ok with a variable but not inline.

So, no inline ++ for us in Javascript?

8
  • 6
    That's not how ++ works. What's wrong with +1? Commented Jul 14, 2013 at 16:54
  • 1
    Well, no ++ for function calls... Commented Jul 14, 2013 at 16:54
  • @32bitkid : nothing wrong, just testing stuff here. Commented Jul 14, 2013 at 16:56
  • A cleaner way to do it would be: $('#TextBox').val(function(){ return parseInt(this.value, 10)+1; }); Commented Jul 14, 2013 at 16:56
  • If you want to have some + signs together in a confusing way that works, do it like this 1 + + "5"; // 6 Commented Jul 14, 2013 at 16:57

3 Answers 3

7

There's nothing particular to jQuery about this. ++ increments a variable. You are trying to increment the return value of a function call.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes. ++ is an operator that only applies to variables and properties of objects.
then why is parseInt($('#TextBox').val()) + 1 working fine ?
@Gloserio ++ performs an assignment , where are you changing a property/variable value here? It's for the same reason 1++ doesn't work and 1+1 does. See the language specification on the Postfix incremenet operator.
@Gloserio — + doesn't modify a variable.
I think the "real" reason is that + 1 produces the value of one more, ++ post-increments (returning current value)
|
4

Q: What does x++ mean?

A: x++ means take the value of x, let's call this n, then set x to be n + 1, then return n.

Q: Why does this fail on a non-variable?

A: Let's try it on something simple, say 3, and see where things go wrong.

  1. Take the value of 3 and call it n, okay, n = 3

  2. Set 3 to be n + 1, so 3 = 3 + 1, 3 = 4 this makes no sense! So if this step can't be done, the ++ operator can't be used.

1 Comment

Lols, I can actually even make you even more mad if I tell you I know this :p
0

++ works on variables, not directly on numbers

var c = parseInt($('#TextBox').val());
$('#TextBox').val( ++c );

Change the order from

var x = 0;

var result = x++;

result // 0

To

var x = 0;

var result = ++x;

result // 1

Then it will evaluate ++ before retrieving the value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.