Javascript Loop explanation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 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

15th Jan 2018, 3:15 PM
Azrin Hamdan
Azrin Hamdan - avatar
7 Answers
+ 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
15th Jan 2018, 3:25 PM
Burey
Burey - avatar
+ 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 :(
16th Jan 2018, 8:09 AM
visph
visph - avatar
+ 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? ;)
15th Jan 2018, 3:58 PM
visph
visph - avatar
+ 5
What's << clarification peeps >>? Google doesn't translate it ^^
16th Jan 2018, 5:38 AM
visph
visph - avatar
0
Ouhh, now I get it. Thanks for the clarification peeps. Much appreciated
16th Jan 2018, 5:35 AM
Azrin Hamdan
Azrin Hamdan - avatar
- 1
@visph Sorry about that, I’m new to SoloLearn and I don’t know the customs. Sorry for being rude.
17th Jan 2018, 5:31 AM
Azrin Hamdan
Azrin Hamdan - avatar
- 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".
5th Dec 2020, 2:08 AM
Emmanuel Riano
Emmanuel Riano - avatar