Reputation: 1
var x = 0;
var arr = [4,9,2];
arr[x] = (++x)-1;
document.write(arr[x]);//9
//Why js ignores minus that outside of brackets? Why is it 9 not 4?
Upvotes: 0
Views: 56
Reputation: 655
arr[0] = 0
, herex
incremented by 1 so,x
= 1, (1)-1 = 0
arr[1]
will print 9 becausex
= 1 , you are accessing the array element with index 1
document.write(arr)
it will print[0,9,2]
,because the first element of the array (with index 0) would be assigned the value 0.
var x = 0;
var arr = [4,9,2];
arr[x] = (++x)-1;
// x would be 1 after the evaluation of this statement.
//document.write(x);// it will print 1
document.write(arr[x]);// arr[1] it will print 9
//document.write(arr);// it will print [0,9,2]
Upvotes: 0
Reputation: 386868
Basically this with prefix increment
++x - 1
is the same as the use of x with a postfix increment.
x++
Upvotes: 0
Reputation: 56
you write to
arr[x] // which is arr[0]
(++x)-1; // 1-1 = 0, x = 1
then you write out
document.write(arr[x]); //arr[1] which is 9
Why js ignores minus that outside of brackets?
so no, js does not ignore the minus. Maybe try to understand the prefix ++
operator wtthout using arrays, since they confused you a bit in this case.
Example:
var x = 0, y = 0;
y = (++x) - 1;
document.write("x: " +x + " y: " y); //x == 1, y == 0
Upvotes: 1
Reputation: 53958
This (++x)-1
would result in 0 and the x
would be 1 after the evaluation of this statement, since you have incremented it by 1 and it was assigned the value of 0.
So this arr[x]
(in the statement document.write(arr[x]);
) is actually arr[1]
and arr[1]
is assigned the value of 9.
Regarding the assignment:
arr[x] = (++x)-1;
Now the value of the first element of the array (with index 0) would be assigned the value 0. This is why if you print the arr you will get the following output:
[0,9,2]
Upvotes: 2