Execution of postfix ++ operation - javascript

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

Related

Operator precedence ' ++ ' JavaScript [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.

trouble understanding call-stack within a function

I currently am learning Javascript and C.S fundamentals, I am completing an assignment which was to create a function that takes a value(num) and outputs the index value within fibonacci numbers.
Example: function(6) outputs 8; because 8 is the 6th number in the fibonacci sequence.
fibonacci numbers: 1,1,2,3,5,8
index position: 1,2,3,4,5,6
below is the solution to the problem.
const fibonacci = function(count) {
let a = 0;
let b = 1;
for (let i = 1; i < count; i++) {
const temp = b;
b = a + b;
a = temp;
}
return b;
};
The part I am having trouble understanding lies within the for-loop, from what I've gathered it seems this is how it's being executed within the call-stack:
execute b + a
store the previousValue of b in temp
a is now equal to temp/previousValue
execute b + a
update value of a...
but what I struggle to understand is why a stores the previousValue of B and NOT the currentValue.
When I envision the call-stack running I expected the output to look something like this;
0,1
1,1
2,2
instead of..
0,1
1,1
1,2
The value of a remains at 1 even though b is now equal to 2, after
temp = b;
b = 1;
a = 1;
b = a + b // 2;
a = temp;
a should be equal to 2 now, but instead it remains at 1; Why?
If I understand you correctly, your misunderstanding is here:
a is now equal to temp/previousValue
The value stored in a does not change until the last operation in the loop body. With the initial values of a=0; b=1;, when the loop body runs,
temp is set to the value of b, so temp=1;
b is set to a+b, so b=1
a is updated with the value in temp, so a=1
At the end of each loop, b holds the next Fibonacci value. The value in a is updated to the previous value only so that it can be used in the next iteration of the loop to calculate the new value of b.

ES6 +new Javascript Syntax [duplicate]

I'm trying to understand unary operators in javascript, I found this guide here http://wiki.answers.com/Q/What_are_unary_operators_in_javascript most of it makes sense but what I don't understand is how the following examples would be used in an actual code example:
+a;
-a;
To my understanding the +a; is meant to make the variable the positive value of a and the -a; is meant to make the variable the negative value of a. I've tried a number of examples like:
a = -10;
a = +a;
document.writeln(a);
And the output is still -10;
I've also tried:
a = false;
a = +a;
document.writeln(a);
And the output is 0;
What is a practical code example of these unary operators?
The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.
var a = 4;
a = -a; // -4
a = +a; // -4
The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.
var a =-4;
a = Math.abs(a); // 4
Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.
var a = "5";
a = +a; // 5
The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.
var a = "5";
a = parseInt(a, 10); //5
One example is that they can be used to convert a string to a number,
var threeStr = '3.0'
var three = +threeStr
console.log(threeStr + 3) // '3.03'
console.log(three + 3) //6
I would like to explain this from basic mathematical point:
The multiplying rules:
Positive x Positive = Positive: 3 x 2 = 6
Negative x Negative = Positive: (-2) x (-8) = 16
Negative x Positive = Negative: (-3) x 4 = -12
Positive x Negative = Negative: 3 x (-4) = -12
Considering you example:
a = -10;
a = +a
document.writeln(a);
+a = +(-10) = Positive x Negative = Negative = -10
a = false;
a = +a;
document.writeln(a);
false == 0, +a = +(+0) = Positive * Positive = Positive = 0 (maybe use true is a better example)
a = 1
b = -a
console.log(b)
output
-1
'+' operator in a variable 'a' simply means : a
'-' operator in a variable 'a' simply means : -a
Since, in above example
a=-10;
a= +a; // means a, ie, +(-10) which is -10
but,
a= -a; // means -a, ie, -(-10) which is +10
+a means a*1
and
-a means a*(-1)
Thats it!!!!!!
Try this
false == 0 // returns true
So,
a = false
a = +a //a * 1
console.log(a) // prints 0 as expected

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