Here's a test situation for using the unary operator "++":
var j = 0 ; console.log(j); j = j++; console.log(j);
For this, the output is:
0 0
Since the ++ operator's position is at the back of the operand, so its precedence is lower than the assignment's precedence, I would expect "j" to first receive the value of itself (i.e.0), but then be incremented. So why is the second console.log(j)
call still showing "0"?
Just to be clear, I know that the solutions are:
// 1) j++; // 2) ++j; // 3) j += 1; // 4) j = ++j;
But I need to know why the increment step is not conducted in this specific scenario, NOT how to fix it!
In mathematics, an unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : A → A, where A is a set.
Which is the correct example of a unary operator? Explanation: &, == and / requires two operands whereas — requires only one operand, in general, it decreases the value of operand by 1.
Explanation: Unary operator as the name suggests is used to process the only one operand.
The select, project, and rename operations are called unary operations, because they operate on one relation.
This is an unintuitive (but not "weird"!) behaviour when using post-increment.
The statement j = j++
does this:
foo() = j++
j
(0), and remember it as the result;j
(to get 1);j
(0).The result is a no-op.
The key here is that the entire RHS is evaluated and the post-increment performed, before the final assignment.
http://www.ecma-international.org/ecma-262/5.1/#sec-11.3.1
http://www.ecma-international.org/ecma-262/5.1/#sec-11.13.1
According to the ECMA Specifications for Postfix Increment Operator,
- 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.
So, it is clear that the new value is first set on the lhs
(in this case j
) and the the old value is returned as the result of the expression, which is again set back in j
. So, the value doesn't change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With