The “If” is confusing. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

The “If” is confusing.

for (i = 0; i <= 10; i++) { if (i == 5) { break; } document.write(i + "<br />"); } Hello, isn't it the “If” is only executed with true? Then why it is still executed even tho the “i” is equivalent to 10? And 10 isn't equal to 5. Please explain it to me. Thanks!

25th Dec 2017, 1:57 AM
Vincent Matthew Benito
Vincent Matthew Benito - avatar
4 Answers
+ 5
Lemme translate that into pseudo code. Setting i to value 0. If i equals 5, stop. Else, increment i. Repeat this process until i reaches 10.
25th Dec 2017, 2:10 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 4
Hey, have you actually tried running this to see it in action, I just did and it did what I expected. Try it for yourself and if you are still unsure I will try to explain where you may be slightly incorrect
25th Dec 2017, 2:04 AM
Tarantino
Tarantino - avatar
+ 2
break is a build in function or method for (for loop, while loop, do loop) that stop running that section of code when called. {so no matter what's in here break; exits this bracket} sololearn has a section on this. should check it out.
25th Dec 2017, 5:34 AM
Dick Tracy
Dick Tracy - avatar
+ 1
I alway place print statements around code I want to visually inspect while running. See the following: for (i = 0; i <= 10; i++) { if (i == 5) { document.write("not 5a </br>"); //break; continue; document.write("not 5b </br>"); } document.write(i + "<br />"); } If you run the following code, you can see that “continue” or “break” will skip the line below it. However “break” will exit the loop, while “continue” will allow the loop to continue. If you really want to make sure that another loop will not execute you can set i =12;
25th Dec 2017, 2:40 AM
H Chiang