JavaScript ++ operator not working correctly - javascript

Why is it that when I run the JavaScript code below, it alerts 10? I would expect it to alert 11. I tried this in multiple browsers.
var t=5;
t+=t++;
alert(t);

Let's rewrite it a couple times to expand out each step, assuming t = 5
t += t++;
// same as
t = t + t++;
// same as
t = 5 + t++;
// same as
t = 5 + (t = t + 1, 5); // the second 5 here is the old `t` value
// same as
t = 5 + 5; // the `t = t + 1` becomes obsoleted by the other `t =`
// same as
t = 10;
So what have we learnt? Write it longhand,
t = t + t + 1;
// or
t = 2 * t + 1;
// or if you really like +=
t += t + 1;
If you're wondering why t++ is the same as (t = t + 1, 5), it is because of how foo++ is defined, it means
Remember the value of foo, lets call this old_foo
Increment foo by 1
Return old_foo
If we were to write it as a function, pseudocode
function (foo) { // passing foo by reference
var old_foo = foo;
foo = foo + 1; // imaging this is a reference set
return old_foo;
}
Or, using the comma operator,
foo = foo + 1, old_foo;
// i.e. if `foo` was `5`
foo = foo + 1, 5;

It's because you used t++ instead of ++t
The first one evaluates the number first then increments, whereas the second does the opposite.
t = 5; t += ++t // => 11

You seem to assume that given left += right, right is evaluated first and then added to left. However, that is not the case.
From the spec:
12.14.4 Runtime Semantics: Evaluation
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
Let lref be the result of evaluating LeftHandSideExpression.
Let lval be GetValue(lref).
...
As you can see, the left side is evaluated before the right side, i.e. t is evaluated before t++, and at that point t is still 5.

Related

Why position of increment operator matters [duplicate]

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.

Incremental issue in JS recursion [duplicate]

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.

JavaScript difference between ' ' and (' ')

What is the difference between '' and ('')
let n = 'a' + 1
let n = ('a') + 1
let n = ('a') + (1)
what is the difference?
They are same both.
() is important for precedence especially if there is math operations and concat with string together. Read this info
var example1='x' + (1+2); console.log(example1);
var example2='x'+1+2; console.log(example2);
var example3=("x"+4)/2; console.log(example3);
var example4=("x")+(4/2); console.log(example4);
Taking a property from an object works without parentheses.
var value = { x: 1 }.x;
console.log(value);
Basically the only need for parenthesis is to destructure the item ouside of a declaration.
Does not work
var foo;
{ foo } = { foo: 1 }; // assigment to a block statement
console.log(foo);
Works
var foo;
({ foo } = { foo: 1 });
console.log(foo);
Another use case for parentheses, is by takeing an arrow function which returns an object.
var fn = foo => ({ foo });
console.log(fn(1));
There’s no difference between '' and (''). Parentheses make no difference in your code examples.
Parentheses (), known as the Grouping Operator, are used to change the order of evaluation of an expression. Consider the following expression:
1 + 2 * 3
As the * operator has higher precedence, first 2 * 3 will be evaluated and then the result of multiplication will be added to 1.
const result = 1 + 2 * 3;
console.log(result);
If you want to do addition first, then you can use ().
(1 + 2) * 3
Adding parentheses will change how the expression is evaluated. Instead of multiplication, now 1 + 2 will be evaluated first and then the result of addition will be multiplied with 3.
const result = (1 + 2) * 3;
console.log(result);
Grouping Operator ()
Grouping operator implies the precedence of evaluation of an expression or subexpression.
With the grouping operator, it is possible to override the normal precedence of evaluation by telling the compiler an expression with lower precedence should be evaluated before an expression with higher priority.
console.log(3 + 4 * 5); // 3 + 20
// expected output: 23
console.log(4 * 3 ** 2); // 4 * 9
// expected output: 36
let a;
let b;
console.log(a = b = 5);
// expected output: 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Javascript operator precedence question: i = i— + ++i

Please consider this snippet of code:
var i = 1;
i = i-- + ++i;
My understanding of the order in which the operators & operands are processed is as follows:
i is incremented by 1 (pre-fix increment)
i is added to i( addition )
i is decremented by 1(post-fix decrement)
The value of the right hand side is assigned to i (assignment operation)
If my understanding is correct, i should end up having a value of 3. However, I printed out the result using some online javascript interpreter, and the end value of i is 2.
Where did I get wrong?
var i = 1;
i = i-- + ++i;
this is how the compiler will go about working through this code
create a variable called i
set the value of i to 1
(rhs first element) take value of i (1) decrement value (i is now 0)
(rhs second element) increment value of i (i is now 1)
set the value of i to rhs (2)
JavaScript always evaluates subexpressions in a left-to-right order, and then applies the operator:
// parentheses added for clarity
i = (i--) + (++i); // i = 1
i = 1 + (++i); // i = 0 after i--
i = 1 + 1 ; // i = 1 after ++i
i = 2 ;
Understanding the logic with precedence values:
var i = 1;
i = i-- + ++i;
prefix increment(++i) precedence = 17
postfix decrement(i--) precedence = 16
addition(+) precedence = 14
i = 1 + 1
i = 2
More precedence related info can be found in,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Confusion About Operator Precedence

Im going through the 'Grammer' chapter in Kyle's You Dont Know Js.
As per this link at MDN, ...++ Postfix increment has a higher precedence over = & even ++... Prefix increment. Yet, in javascript, the following code seems to prove otherwise.
var a = 1;
var b = a++; // b = 1; a = 2;
var c = ++a; // c = 3; a = 3;
What am I getting wrong? Doesn't the above code show that = & ...++ Postfix increment have a higher precedence over = & ++...?
The order of evaluation is (from high precedence to low): postfix operator a++, prefix operator ++a, addition operator + (from left-to-right), and the assignment operator =, from MDN.
Take a look at the following:
var a = 1;
var b = a++ + ++a + a++;
// The order is:
// b = 1 + ++a + a++;
// b = 1 + ++a + 2;
// b = 1 + 4 + 2;
// b = 7; a = 4;
The order of evaluation is maintained, just that the postfix operator increments the value of a after the last operation has finished, i.e. the assignment operator.

Categories