I find this a bit confusing. HELP! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I find this a bit confusing. HELP!

var x = 0; var arr = [4, 9, 2]; arr [x] = (++x) - 1; document.write(arr[x]); // This outputs 9. why?

2nd Mar 2018, 2:44 PM
Briaה‎
4 Answers
+ 12
(++x) -1=0 and ++x done pre increment first then use so x become 1 so arr[1] is second element of array which is 9 arr[x] =arr[1]=which is 9
2nd Mar 2018, 3:04 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 3
I will bare what it is below: var x = 0; // x is 0, initial value var arr = [4,9,2]; // array with initial values of 4,9,2 arr[x] = (++x) - 1; // arr[0] = (0+1) - 1; // At this point, arr[0] is 0, x is 1 because of the increment When you want to print the value of arr[x] here, it is no longer arr[0], but arr[1]. This is because the x value is already 1 and not 0. Thus, arr[1] = 9. If you print arr, you will get [0,9,2] and not [4,9,2]. Hope this helps :)
2nd Mar 2018, 3:07 PM
Deddy Tandean
+ 3
arr [x] = (++x) - 1; In JavaScript, left side is evaluated first. Since x is 0 before this statement, arr[0] is set aside as a memory location to be stored, then it goes on to calculate the right side expression. x is incremented to 1 and RHS = 0, since we pre-calculated the location to store this value, 0 is assigned to arr[0], but now x has become 1 so you are printing arr[1], which is 9.
2nd Mar 2018, 3:15 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
+ 1
Question is tricky and it tests our knowledge of incremental operators in terms of their assignment and not in terms of their evaluation. var x = 0; var arr = [4, 9, 2]; arr [x] = (++x) - 1; // whether ++x or x++ it only equates arr[0] to 0(incase of ++x) or -1 (incase of x++) // x value is now 1 even if the equation was :- arr[x] = (x++) - 1; document.write(arr[x]); // arr[1] is displayed . That is 9.... Whether post increment or pre increment, the value of x after the evaluation and assignment is incrimented. ( 1 in this example)
18th Jun 2018, 9:18 AM
Mano Ekambaram
Mano Ekambaram - avatar