Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?

Tags:

javascript

I have a very simple arithmetic operator but am at my wits end why it doesn't return 2. The code below returns 1. I thought that x++ equates to x = x + 1;

CODE

var x = 1;
document.write(x++);

However if I run the code as follows, it returns 2 as expected

CODE

var x = 1;
document.write(++x);

What am I doing wrong?

like image 999
PeanutsMonkey Avatar asked Jun 27 '12 01:06

PeanutsMonkey


2 Answers

PostIncrement(variable++) & PostDecrement(variable--)

When you use the ++ or -- operator after the variable, the variable's value is not incremented/decremented until after the expression is evaluated and the original value is returned. For example x++ translates to something similar to the following:

document.write(x);
x += 1;

PreIncrement(++variable) & PreDecrement(--variable)

When you use the ++ or -- operator prior to the variable, the variable's value is incremented/decremented before the expression is evaluated and the new value is returned. For example ++x translates to something similar to the following:

x += 1;
document.write(x);

The postincrement and preincrement operators are available in C, C++, C#, Java, javascript, php, and I am sure there are others languages. According to why-doesnt-ruby-support-i-or-i-increment-decrement-operators, Ruby does not have these operators.

like image 136
Josh Mein Avatar answered Oct 23 '22 01:10

Josh Mein


I think of x++ and ++x (informally) as this:

x++:

function post_increment(x) {
  return x; // Pretend this return statement doesn't exit the function
  x = x + 1;
}

++x:

function pre_increment(x) {
  x = x + 1;
  return x;
}

The two operations do the same thing, but they return different values:

var x = 1;
var y = 1;

x++; // This returned 1
++y; // This returned 2

console.log(x == y); // true because both were incremented in the end
like image 33
Blender Avatar answered Oct 23 '22 00:10

Blender