+ 6

Looping through an array

Can someone please explain to me why the answer to this is 0 and not 3.? When looping through the array, doesn’t it stop at 3? Wouldn’t 3 therefore be what I multiplied? var arr = [1,2,3,4]; var x = 1; for (var i = 0; I < arr.length; i++); { x*=i; } alert (x);

21st Apr 2018, 1:04 PM
Levi
Levi - avatar
6 Respuestas
+ 10
It doesn't stop after the first iteration. Observe the code carefully. The loop content is x *= i and the value of x is printed after the loop ends. 1 multipled by 0 is 0. 0 is assigned to x. 0 multipled by 1 is 0. 0 is assigned to x. 0 multipled by 2 is 0. 0 is assigned to x. 0 multipled by 3 is 0. 0 is assigned to x. x is printed. 0 is printed.
21st Apr 2018, 1:25 PM
Hatsy Rei
Hatsy Rei - avatar
+ 10
On the first iteration, the value of i is 0. Anything multiplied by 0, is 0.
21st Apr 2018, 1:08 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
It doesn't stop. after the first iteration x=0 then i =1,2,3,4 and x = x*i =0 That's why its 0
21st Apr 2018, 1:24 PM
Akib
Akib - avatar
+ 3
By the way, the alert function is outside of the for loop.
21st Apr 2018, 1:24 PM
Ibaadi Jaya
Ibaadi Jaya - avatar
+ 2
So it stops after the first iteration not the last? I thought it would loop through them all. So the answer would be 0123. Thanks Hardy
21st Apr 2018, 1:09 PM
Levi
Levi - avatar
+ 1
Got it!! Thanks Hatsy. Perfect explanation. Thank you all.
21st Apr 2018, 1:27 PM
Levi
Levi - avatar