Looping through an array | Sololearn: Learn to code for FREE!

+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);

4/21/2018 1:04:33 PM

Levi

6 Answers

New Answer

+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.

+10

On the first iteration, the value of i is 0. Anything multiplied by 0, is 0.

+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

+3

By the way, the alert function is outside of the for loop.

+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

+1

Got it!! Thanks Hatsy. Perfect explanation. Thank you all.