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.

29th Sep 2018, 6:46 PM
Daniel
Daniel - avatar
2 Antworten
+ 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.
29th Sep 2018, 7:16 PM
Shadow
Shadow - avatar
0
like Shadow said it's because the answer (equation) is always executed before the variable
29th Sep 2018, 8:28 PM
Spider38E
Spider38E - avatar