0
Can someone please explain why this JavaScript output behaves this way?
var x = 0 x = (++x)-1 console.log(x) //output is 0 var x = 0; var array = [2,9,7,4]; array[x] = (++x)-1; console.log(array[x]); //output is 9 I’m having trouble understanding why the second scenario x is treated as a 1 and not a zero. I would have expected output for console.log(array[x]) to be 2. Please help.
2 odpowiedzi
+ 1
X equals 1 because in the line
array[x] = (++x) - 1;
x is incremented, so it becomes 1. Don't let the -1 afterwards fool you, it doesn't affect the original value of x since it only works with a copy of that value.
0
like Shadow said it's because the answer (equation) is always executed before the variable