Operator precedence ' ++ ' JavaScript [duplicate] - javascript

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.

Related

How does this Math.random() code work when used with brackets? [duplicate]

When I do something like this:
var x = 5;
console.log( x + (x += 10) ); //(B) LOGS 10, X == 20
console.log( (x += 10) + x ); //(A) LOGS 0, X == 30
The difference in the returned value between (A) and (B) is explained by the value of x at the time it becomes evaluated. I figure that backstage something like this should happen:
TIME ---->
(A) (x = 5) + (x += 10 = 15) = 20
(B) (x += 10 == 15) + (x == 15) = 30
But this only holds true if and only if x is evaluated in the same left-to-right order that it was written.
So, I have a few questions about this,
Is this guaranteed to be true for all Javascript implementations?
Is it defined to be this way by the standard?
Or, is this some kind of undefined behavior in Javascript world?
Finally, the same idea could be applied to function calls,
var x = 5;
console.log(x += 5, x += 5, x += 5, x += 5); // LOGS 10, 15, 20, 25
They also appear to be evaluated in order, but is there a stronger guarantee that this should always happen?
Is this guaranteed to be true for all Javascript implementations?
Yes.
Is it defined to be this way by the standard?
Yes, you can read it yourself here.
Specifically, the runtime semantics: evaluation of the addition operator (+) specify that the left expression is evaluated before the right expression.
It's the same for the evaluation of argument lists.
Or, is this some kind of undefined behavior in Javascript world?
Yes, there is undefined behaviour in JavaScript, but not here.

Why doesn't this for loop read this in passed argument properly?

Below is my code
function generateGrid(spacing, boundBox, geometry) {
console.log(spacing);
console.log(boundBox);
var grid = [];
console.log(spacing);
for (var x = boundBox[0]; x < boundBox[2]; x = x + spacing) {
for (var y = boundBox[1]; y < boundBox[3]; y = y + spacing) {
if(geometry.intersectsCoordinate([x, y])) grid.push([x, y]);
console.log(boundBox[3] - y)
}
console.log(boundBox[1] - x)
}
console.log(grid);
}
If spacing is replaced by a number like 10000 the for loop executes fine.
From your Console screenshot it looks like the passed in argument is the string "10000" rather than the number 10000.
Either check the code that's calling your function, or convert to an integer inside the function, for example by using parseInt(spacing).
As a tip to help with spotting any similar issues in the future, Chrome's console.log shows numeric values in blue and string values in black.
x is a number so use String(x) so you use operator + between two strings, that would give you "15" + "1" = "151", but that is probably not what you wanted

Execution of postfix ++ operation

How does a postfix ++ operator works :
var a = 100;
var b = a++ + a;
//Result 201
Here if 'a' is incremented then should not the value be 202. And if it is true then should not be the next equation value 301 ?
var a = 100;
var b = a++ + a + a;
//Result 302
In
var a = 100;
var b = a++ + a;
what happens is:
a is set to 100
a++ is evaluated. The value of that subexpression is 100. Also, a is set to 101.
The value of a (101) is added to the value of the left-hand subexpression (100).
b is set to the result, 201.
The postfix ++ operator returns the value of the variable as it was before the increment. The prefix ++ operator (as in ++a) performs the increment and gives the value after that.
The behavior in JavaScript is the same as in many other languages with expression syntax and semantics derived from C.
Postfix means get value first and then increment.
Your result is
100 (add one to a) + 101

Javascript increment while assigning

I was having a conversation about the prefix increment operator, and we seem to have run into a disagreement.
When running this code:
var x = 0;
x = ++x;
is the second line equivalent to:
x = (x = x + 1) OR
x = (x + 1)
It is hard to tell the difference because the results are identical (both result in x having a value of 1)
I believe that the value is not saved to the original variable when the left hand side of the assignment is the variable itself.
My counterpart disagrees and thinks the value is saved to the original variable whenever the ++ operator is used.
Which one of us is right?
It is saved, so it is similar to the first example.
Take for example this code:
var v = 0;
v = ++v + ++v + ++v;
// Returns 6
That is because this will translate to:
v = (0+1) + ((0+1)+1) + (((0+1)+1)+1);
Or, to be more accurate:
v = 0+1 +
v = 1+1 + //Previous value of v + 1
v = 2+1 //Previous value of v + 1
Why?
++v will first save the incremented value of v, then it will return this incremented value.
To simplify things, try this in your console:
x = 0;
++x;
If ++x would resolve to x + 1, the value of x would now still be 0, right?
Nope, your x will be 1. This means that ++x must have a assignment operator in there.
Just try writing both ++x and x++ out in full English sentences:
++x: increment x by one and return the value
x++: return the value of x, and increment it.
Your second line (x = ++x;) is equivalent to x = (x += 1), yes.Just look at any loop you've ever written:
for (var i = 0;i<100;i++)//<-- no need for another assign here
So you could've written ++x; all the same, but since that expression is the entire statement, it makes no difference if you write x++; or ++x...
As you probably know xxsomeVar increments the variable by 1, assigns the resulting value to that variable and then returns it, someVar++ returns the current value of the variable, and then increments it by 1 (the new value is assigned to the variable, too, of course).
So ++x; is the equivalent of x = (x + 1);
From the Language specs:
++prefix increment operator
Postfix++ increment operator
Doing:
var x = 0;
console.log(++x); // will make print 1
Doing :
var x = 0;
console.log(x++); // will make print 0
console.log(x); // will print 1
After reading the ECMAScript Language Specification in answer to the question it appears that ++x is equivalent to x = ( x = x + 1 ).
Translation of the steps outlined by the specification is:
The result of the operation will be assigned to x
Throw error if certain conditions are true
oldValue = x
newValue = oldValue + 1
assign newValue to x
return newValue
For the post-increment operator the above will return the oldValue instead of the newValue.
var x = 0;
// x is assigned 1 during the post-increment operation but because
// the oldValue is returned it is immediately replaced by 0.
x = x++;
console.log( x ) // prints 0

++someVariable vs. someVariable++ in JavaScript

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.

Categories

Resources