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;
C
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;
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.
If you take a look at the javascript specification pages 70 and 71 you can see how it should be implemented:
Prefix:
- Let expr be the result of evaluating UnaryExpression.
- Throw a SyntaxError exception if the following conditions are all true:72 © Ecma International 2011
- Type(expr) is Reference is true
- IsStrictReference(expr) is true
- Type(GetBase(expr)) is Environment Record
- GetReferencedName(expr) is either "eval" or "arguments"
- Let oldValue be ToNumber(GetValue(expr)).
- 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(expr, newValue).
- Return newValue.
Or more simply:
Postfix:
- Let lhs be the result of evaluating LeftHandSideExpression.
- Throw a SyntaxError exception if the following conditions are all true:
- Type(lhs) is Reference is true
- IsStrictReference(lhs) is true
- Type(GetBase(lhs)) is Environment Record
- GetReferencedName(lhs) is either "eval" or "arguments"
- 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.
Or more simply:
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