- 1
Javascript Loop explanation
Please help to explain the following Javascript loop. I donât understand how (Sum + =i) will result in the value of 16. If sum=0 shouldnât it be 8? Since the value of âsumâ was not changed in the loop. var sum=0; for(i=4; i<8; i++){ if(i==6){ continue; } sum + = i; } document.write(sum); Output will therefor be 16
7 RĂ©ponses
+ 10
follow this loop table
i sum
4 0+4=4
5 4+5=9
6 loop skipped by continue
7 9+7=16
8 8 < 8 is false therefore the loop ends here
sum ends at 16
+ 6
Well, google doesn't translate "peeps" in the whole sentence, but do it as single word: it seems to be slang/argot for "friends" ^^
So, @Azrin: don't call me your friend, as you've initially marked my answer as best and immediatly retrieve it without any upvote...
I'm so disapointing of sololearners attitude: I think I've given a lot of help in Q&A, and even I was previously discouraged, I came back after about 1-2 months of inactivity, but that's too much (@Azrin is not the only one, it's a general case, even there's some exception) all the more that sololearn doesn't make anything to improve things, as they just privilegiate to get more and more users than a good quality content. I was expecting a lot of this app' and of this community but I was wrong :(
+ 5
@Azrin Hamdan wrote: << the value of âsumâ was not changed in the loop. >>
You're wrong: the value of 'sum' is changed in the loop...
Anyway I don't really know where is your confusion but I can guess two possibility:
+ you doesn't good understand how operate 'sum += i' : it's same as 'sum = sum+i'
+ you bad read the code, because of the unstrict indentation used... so code better indented is:
var sum=0;
for(i=4; i<8; i++) {
if(i==6) {
continue;
}
sum + = i;
}
document.write(sum);
... can you see now that 'sum' is changed in the loop? ;)
+ 5
What's << clarification peeps >>? Google doesn't translate it ^^
0
Ouhh, now I get it. Thanks for the clarification peeps. Much appreciated
- 1
@visph Sorry about that, Iâm new to SoloLearn and I donât know the customs. Sorry for being rude.
- 1
So "i" starts at 4, and loops and prints 5 and skips 6 and prints 7 and i is less than 8 so its not equal to 8 and doesnt print it and adds 4,5, and 7 to the sum of 16. "Sum is addition".