New course! Every coder should learn Generative AI!
Try a free lesson+ 5
The output of the code gives 2 but I don't understand why??
var arr = []; for(var i = 5; i > 0; i--) arr.push(i); console.log(arr[3]);
4 Answers
+ 9
The loop makes these assignments:
arr[0] = 5
arr[1] = 4
arr[2] = 3
arr[3] = 2
arr[4] = 1
+ 7
Explaining the for loop:
arr changes from:
[]
To
[5]
To
[5,4]
To
[5, 4, 3]
To
[5, 4, 3, 2]
To
[5, 4, 3, 2, 1]
Since 2 is the 4th element, it is the one represented by arr[3]
+ 5
Or simply 5-3=2
+ 4