Increasing Understanding Of Javascript Increment Operator
Solution 1:
The post-increment operator increments after its value is taken. That's what makes it different from the pre-increment operator.
Solution 2:
var y = x++;
Is shorthand for these two statements (in order):
var y = x;
x = x + 1;
If you want y to equal 4 you would do:
var y = ++x;
which is short hand for:
x = x + 1;
var y = x;
Solution 3:
The question has been improved by following the Alex comments.
Suppose to have a variable x
, s.a. var x=3
.
CASE 1 When you write:
var y = x++;
then, the following steps are done:
- the variable
x
is evaluated (x
is 3); - the variable
x
is incremented (x
is 4); - the result of the evaluation (happened in step (1)) is assigned to
y
(hence will resulty=3
);
CASE 2 When you write: var y = ++x;
then, the following steps are done:
- the variable
x
is incremented (x
is 4); - the variable
x
is evaluated (x
is 4); - the result of the evaluation (happened in step (2)) is assigned to
y
(hence will resulty=4
);
It is important to follow the operators precedence for Javascript (e.g., see more here) in this cases.
CASE 3 For sake of completeness, as observed by Alex, it is also important to recognize that if the steps provided in CASE1 are repeated on the same variable, then the variable will be incremented and then restored to the initial value, i.e. when you write:
x = x++;
then, the following steps are done:
- the variable
x
is evaluated (x
is 3); - the variable
x
is incremented (x
is 4); - the result of the evaluation (happened in step (1)) is assigned to
x
(hence will resultx=3
);
Solution 4:
From the MDN Docs - Arithmetic Operators
++ (Increment)
The increment operator is used as follows:
var++ or ++var
This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.
For example, if x is three, then the statement y = x++ sets y to 3 and increments x to 4. If x is 3, then the statement y = ++x increments x to 4 and sets y to 4.
Solution 5:
The ++
after the variable is a post increment operator meaning the increment is performed after the variable is read.
See: http://en.wikipedia.org/wiki/Increment_and_decrement_operators
Post a Comment for "Increasing Understanding Of Javascript Increment Operator"