0

Why the output is 4? May someone explain it to me because i'm stupid as hell..

var arr=[1,2,3,4]; var x=0; for(var y=0; y<arr.length; y++) { if(y%2==0) x+=arr[y]; } document.write(x);

24th Dec 2016, 4:53 PM
Wolfinho
9 Answers
+ 4
Read it line by line. the array contains value 1 , 2 , 3 and 4 in elemental order. In the loop, you notice this : if(y%2==0) , so just find something which divided by 2 gives no leftover. That something , which is a value, would be the element number which will be added into 'x'
24th Dec 2016, 5:00 PM
Wen Qin
Wen Qin - avatar
+ 2
because 4!<arr.length
24th Dec 2016, 5:03 PM
Wolfinho
+ 2
You got 1 from first run of this loop. Because, (0%2)= 0. So, after the first run of this loop the variable X value should be 1 (x += arr[0]).
3rd Jan 2017, 6:43 PM
Kazi Maruf
Kazi Maruf - avatar
+ 1
yes, and that is just 2.
24th Dec 2016, 5:02 PM
Wolfinho
+ 1
Bro i tried to run your code in my machine and you are correct that the output should be 3 but it is displaying 4. This is unexpected. I never thought that something this simple can be this awesome. I will try to apply my brain as much as i can and tell you the answer tomorrow
24th Dec 2016, 5:55 PM
TheNaman047
TheNaman047 - avatar
+ 1
Ok Bro I got your Ans At first run 0%2 == 0 x+=arr[0] which is 1 so x=1 then 2%2 == 0 x+=arr[2] which is 3 so x=4.
24th Dec 2016, 6:51 PM
TheNaman047
TheNaman047 - avatar
0
arr[y]=arr[2], which is 3.. right? that's how i get it.. but it is 4.. how?
24th Dec 2016, 5:05 PM
Wolfinho
0
if you add 5,6 to the array it displays the outpost 9 insted of 8. just can't understand where it finds that 1. also if the array is only [1,2] the outpost is 1. how?
24th Dec 2016, 6:06 PM
Wolfinho
0
thank you, man. i assumed (and was wrong obviously) that 0%2=2, but of course it is 0, there's no leftover.. what a math mistake.. :-) the rest is pretty clear. thank you once again
24th Dec 2016, 7:01 PM
Wolfinho