Skip to content

Instantly share code, notes, and snippets.

@Zirak
Created August 15, 2012 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zirak/3364309 to your computer and use it in GitHub Desktop.
Save Zirak/3364309 to your computer and use it in GitHub Desktop.
postfix and prefix increment

Postfix increment (i.e. n++) is usually explained as such:

  • Tell me the value of n
  • Increment the value of n

And prefix increment (++n):

  • Increment the value of n
  • Tell me the value of n

That is practically correct; however, it is not technically correct. At least not in javascript.

According to the spec, the prefix increment (after being translated into a more humane form and disregarding strict-mode regulations), is this:

  • Save the numerical value of n to T0
  • Increment the value of T0 (without changing it)
  • Store that new value in n
  • Tell me the value of n

And postfix increment:

  • Save the numerical value of n to T0
  • Increment the value of T0 (without changing it)
  • Store that new value in n
  • Tell me the value of T0

So, what's the difference between the practical explanation and the technical one? The main difference is the timeline. In the practical explanation, the increment happens at different times. Technically, it happens in the exact same time - the only difference is which value is being returned.

You may now carry on with your life.

@erikreppen
Copy link

Kicking myself for not wondering why the typical explanation doesn't explain parens failing to force eval as you would expect. The practical explanation doesn't really cover this:

var x=2, y=(x++); //y still equals 2 and now I finally freaking know why. x is never returned in x++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment