For Loop iteration position, have different output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

For Loop iteration position, have different output

What's the difference of the 2 code ---------------code 1------------------- var countOfRooms = 15; // Your code here for (var hotelFloor = 0; hotelFloor <= countOfRooms;){ hotelFloor++; if (hotelFloor == 13){ continue; } console.log(hotelFloor); } ----------code 2-------------- var countOfRooms = 15; // Your code here for (var hotelFloor = 0; hotelFloor <= countOfRooms;){ if (hotelFloor == 13){ continue; } hotelFloor++; console.log(hotelFloor); } For me, They're same, because the if statement inside for loop is considered false and will be skip, unless it's true. But why code 1 is from 1-16(13 not included). While code 2 is infinite. Or near, don't actually know if it's finite or infinite, I use mobile app, but it says execution time out.

23rd Dec 2021, 2:55 PM
Jonathan P. Jundarino
Jonathan P. Jundarino - avatar
4 Answers
+ 2
Because of the continue. It's trapped at 13, because before you increase the value you "restart" the for-loop, where it runs into the if with the same value of 13. It never finishes the for loop, but repeating it with the same value over and over again. This is why you get the timeout message.
23rd Dec 2021, 3:37 PM
Alex
Alex - avatar
+ 1
Alex thanks for the explanation 😂. That's why, I'm still there thinking what's the proplem without you saying. I use phone that's why I can't see the infinite loop. Thanks man, that's great explanation.
23rd Dec 2021, 3:43 PM
Jonathan P. Jundarino
Jonathan P. Jundarino - avatar
0
They are not the same. In code 2 it never reaches the hotelFloor++ when it's on 13.
23rd Dec 2021, 3:11 PM
Alex
Alex - avatar
0
Alex Why? I guess there's output, because is says execution time out and not no output.
23rd Dec 2021, 3:24 PM
Jonathan P. Jundarino
Jonathan P. Jundarino - avatar