difference between a++ and ++a in while loop [duplicate] - javascript

This question already has answers here:
Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?
(3 answers)
Closed 6 years ago.
i am trying to figure out, why do i end up with different outcome, when i use a++ versus ++a in a while loop? i know that they are postfix and prefix operations but still do not get why i am getting the results i get
var a = 1;
while (a < 3) {
console.log(a);
a++;
}
i ger results: 1, 2, 2 , when using ++a instead of a++ i get different outcome.
var a = 1;
while (a < 3) {
console.log(a);
++a;
}
in this case i get 1,2,3.
can someone explain operations order step by step and why do i get the output i get?

You'll only get 1,2,2 or 1,2,3 if you run this in the console - outside the console both will only output 1,2 - check the console when running this fiddle
When running in the console, the last number you see in the console is the "result" of the last operation ... so, 2 (because of post increment) in the first case, and 3 (because of pre increment) in the second -
if you add ONE line after the } with just a; - both will show 1,2,3 - like so
var a = 1;
while (a < 3) {
console.log(a);
a++;
}
a;
and
var a = 1;
while (a < 3) {
console.log(a);
++a;
}
a;
shows that a is the same after the while loop finishes

Related

Object defineProperty confuses the way I think about hoisting / sync and async js [duplicate]

This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 3 years ago.
I thought I had a good understanding of async / sync / hoisting, when it came to how a browser loads data and presents it to the user. However this following example is throwing me for a loop, let me post the example and then explain the question:
var obj = {
counter: 0,
};
Object.defineProperty(obj, 'reset', {
get: function() {
return this.counter = 2;
}
});
Object.defineProperty(obj, "increment", {
get: function() {
return this.counter++;
}
});
Object.defineProperty(obj, "decrement", {
get: function() {
return this.counter--;
}
});
console.log(obj.reset) //2
console.log(obj.increment + ' ' + "incremented") // "2 incremented"
console.log(obj.decrement + ' ' + "decremented") // "3 decremented"
I thought that the way the browser would interpret this would be to run every line of code synchronously which should produce:
//2
//2 incremented
//2 decremented
because if you where to track the changes to 'counter' all the way until the console logs are called, counter would change from 0 to 2 to 3 back down to 2.
And then I thought well wait a second; if the values being returned are not all 2 then maybe calling these console logs is an asynchronous way about getting the data which would then logically lead me to think the result should be:
//2
//3
//2
because if you where to access the 'counter' property upon the time of running the console log then logicly the counter value would change from 0 to 2 upon (obj.reset) and then 3 upon(obj.increment) and then 2 again upon(obj.decrement)
I am obviously wrong about the way im approaching how the browser interprets this and would like a clear step by step explanation of why the values being returned are:
//2
//2 incremented
//3 decremented
if at all possible, thank you.
This has nothing to with asynchronous. console.log is receiving an expression and it's printing that value. obj.increment returns 2 because that's how postfix ++ operator works. It increments the number and returns the value before incrementing. So, it ends up being
console.log(2 + ' ' + "incremented")
console.log() method ends up getting the string 2 incremented. The same logic applies to decrement. The expression becomes console.log(3 + ' ' + "decremented")
did you notice this ?
var cpt_A = 5;
var cpt_B = 5;
function func_A(){ return cpt_A-- }
function func_B(){ return --cpt_B }
console.log ( func_A() ) // return 5.
console.log ( func_B() ) // return 4.
It is a basic of the programming of languages resulting from C. in the case func_A it returns the value of cpt_A, then it does the operation of decrementation. in the case func_B it does the operation of decrementation on cpt_B, then it returns the result.

Postfix operator in JavaScript [duplicate]

This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 4 years ago.
This is a basic JS question I think, but I just couldn't find an answer that I was satisfied with. I'm learning operators in JavaScript and I can't understand this following postfix example and how it works:
var x = 4;
var y = x++;
For example, when I alert x, it gives me 5. But when I alert y, it gives me 4. And I can't understand the logic behind it.
I understand that, because it's a postfix, x is assigned to y. And y reads just x, without the postfix. But why does then the original x read the postfix instead if I'm applying it to a different var?
If I just did var y = x + 1, the original x would stay unchanged. But that's not the case when I use postfix. Why would I even change the x with this method? Couldn't I just go then var x = 4; x++; ? And not bother changing it via another var?
I apologize if this is too basic and thanks in advance!
It's easier to think of the increment operators as little functions that return something. So x++ is a functions that increments x and returns the original value of x, whereas ++x does the same thing but returns the new value.
This comes in handy from time to time especially in loops where you want precise control of the stopping point. For example, compare:
let i = 0, j = 0;
while (++i < 5) {
console.log(i) // stops at 4
}
while (j++ < 5) {
console.log(j) // stops at 5
}
The difference is because the while loop evaluates one before the increment and the other after.
Similarly in recursive functions you'll often see things like:
function recurse(i) {
if (i == 5) return i
console.log(i)
return recurse(++i)
}
console.log("final: ", recurse(0))
But if you use the postfix return recurse(i++) you get infinite recursion.
Why would I even change the x with this method?
For some funny shortforms like:
const array = [1, 2, 3];
let i = 0;
while(i < array.length) console.log(array[ i++ ]);
Couldn't I just go then var x = 4; x++; ?
Yeah or just prefix, like ++x or just x += 1 which is more appropriate in most cases.

Why is the argument passed in to my recursive function not updating its value? [duplicate]

This question already has answers here:
What does x++ in JavaScript do?
(4 answers)
Closed 5 years ago.
I'm just playing around with simple recursion and functions. Nothing too serious, but not doing what I expect:
var recursive = function adder (x) {
x = ++x
if (x < 10) {
console.log('x is now: ' + x)
adder(x)
}
return x
}
console.log(recursive(5))
This completes the loop and runs properly, but am wondering why the 'final' output is '6.' Why don't I get the 'final' value of x after all the recursion is done?
x=++x;
x+=1;
x++;
++x;
You need either the pre increment or the increase by operator, or the postincrement without an reassignment. The post increment retuns first, then increments...
alert((1)++)//1
Some ongoing explanations:
var recursive = function adder (x) {
++x;
if (x < 10) {
console.log('x is now: ' + x)
return adder(x); //lets return our added result
}
return x;//if x=10 lets return 10
}
console.log(recursive(5))//will log 10
It mainly didnt work as expected as primitives are passed by value. So there are actually 5 different x variables in 5 different contexts of adder...
Unlike primitives, objects are passed by reference:
function adder(obj){
obj.x++;
if(obj.x<10){
adder(obj);
}
}
var test={x:1};
adder(test);
console.log(test.x);

Variable changes by itself [duplicate]

This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 5 years ago.
I have a small problem trying to code a snake game in js.
I have this function:
function move() {
var aux = [];
aux = snake.position[snake.position.length - 1];
console.log(aux);
if (snake.direction == 'r') {
snake.position[snake.position.length - 1][1] += 1;
};
console.log(aux);
//updateSnake();
snake.position[snake.position.length - 2] = aux;
updatePosition(snake.position);
};
The problem is that aux is changing itself without me doing anything to it, as you can see. The value from the first console.log is different from the second one! It's not like I'm changing its prototype.
Can you guys help me?
if (snake.direction == 'r') {
snake.position[snake.position.length - 1][1] += 1;
}
The above line is what changes the array aux. The first console.log() returns [10,12] as stated in the above comments. After that, the if statement is incrementing snake.position[snake.position.length - 1][1], which is the value of the variable. When calling console.log() for the second time, the variable aux is evaluated as [10,12+1], equivalent to [10,13], which is the expected result.

Why does this 2d array create unexpected results? [duplicate]

This question already has answers here:
console.log() async or sync?
(3 answers)
Closed 6 years ago.
In the following code, I would expect a 2-dimensional array to be produced, pre-populated with zeros. The problem I am getting is that x[0][3] = 2 seems to be happening too quickly, so by the time of the console log inside the function, the array has a changed value already. I can't seem to remedy this, even with timeouts. What's going on?
function test(size) {
var row = [];
var return_me = [];
for (var i=0; i < size; i++) { row.push(0); }
for (var j=0; j < size; j++) { return_me.push(row.slice()); }
console.log("1:");
console.log(return_me);
return return_me;
}
var x = null;
console.log("0:");
console.log(x);
x = test(5);
console.log("2:");
console.log(x);
x[0][3] = 2;
console.log("3:");
console.log(x);
The unexpected result comes at the "1:" in the output, where I get:
0: 0
1: 0
2: 0
3: 2
4: 0
As Array is an object, you will see the actual (latest) value of that as console.log() shows a reference to the object and by the time you are opening it, the value has changed.
The option is to use console.dir() to print that current state of the object (although console.dir() does NOT work on chrome).
If you want to get the real value in chrome, print that one value, not whole object.
You can look at this post for expanded explanation and more info.

Categories

Resources