How is it possible that the output of the code is zero since we have the value of x set to 1? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

How is it possible that the output of the code is zero since we have the value of x set to 1?

var arr = [1,2,3,4]; var x = 1; for(var i = 0; i < arr.length;i++) { x*=i; } alert(x);

26th Jun 2019, 4:19 AM
eMBee
eMBee - avatar
4 Answers
+ 2
Okay, i in the for loop isn't a representation of the array's elements, but the array's indexes. Indexes start from 0, not from 1, so you'll first be multiplying by 0
26th Jun 2019, 4:30 AM
Airree
Airree - avatar
+ 3
Airree I'm sorry but I still don't understand
26th Jun 2019, 4:27 AM
eMBee
eMBee - avatar
+ 3
Oh okay, thanks Airree
26th Jun 2019, 4:42 AM
eMBee
eMBee - avatar
+ 2
This isn't an enhanced for loop, so if you look at it closely, you don't multiply by arr[i], but by i, which is 0, 1, 2, 3.
26th Jun 2019, 4:21 AM
Airree
Airree - avatar