The output of the code gives 2 but I don't understand why?? | Sololearn: Learn to code for FREE!
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]);

25th Jun 2019, 12:57 AM
eMBee
eMBee - avatar
4 Answers
+ 9
The loop makes these assignments: arr[0] = 5 arr[1] = 4 arr[2] = 3 arr[3] = 2 arr[4] = 1
25th Jun 2019, 1:18 AM
John Wells
John Wells - avatar
+ 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]
25th Jun 2019, 1:35 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 5
Or simply 5-3=2
25th Jun 2019, 2:45 AM
Qasem
+ 4
Thank you, thank you, thank you, John Wells Qasem Prometheus ¯\_(ツ)_/¯ 🇸🇬
25th Jun 2019, 4:42 AM
eMBee
eMBee - avatar