YDKJS Up and Going Loops question

I’ve started reading YDKJS, and in the first chapter of the first book I’ve already found something I can’t figure out. It’s about loops. Kyle writes:

We can use JavaScript’s break statement to stop a loop. Also, we can observe that it’s awfully easy to create a loop that would otherwise run forever without a breaking mechanism.

Let’s illustrate:

var i = 0;

// a `while..true` loop would run forever, right?
while (true) {
// stop the loop?
if ((i <= 9) === false) {

console.log( i );
i = i + 1;
// 0 1 2 3 4 5 6 7 8 9

When I write this in the console, I don’t get the same output, instead I get an infinite loop. I’m guessing it’s because (i <= 9) is never strictly equal to false. When I change the comparison to loose-equals (==), I do get the suggested output.

English isn’t my native language, so it’s possible the pun got lost in translation, as he does say it’s awfully easy to create an infinite loop, but I thought that was about leaving out the breaking mechanism ‘break’. What do you think?

That’s really strange. Which browser are you using? If I copy and paste that code into Safari or Chrome, I get 0 - 9, as expected.

I don’t think you’re misunderstanding the text. All he’s saying is that without the break statement, you’ll get an infinite loop.

There is a strange if condition:

if((i <= 9) === false)

You are telling to JavaScript that if var i is equal to 9 and also this condition is equal to false then try to break the loop. You have mistake in this part.
You can try:

if(i <= 9) {

You shouldn’t be getting an infinite loop, as I too just ran it and it ran as expected (printing out 0 through 9 and then stopping). It might be due to something with your environment, try running your code on a site like www.jsbin.com instead.

The point of the example code is to demonstrate what the break statement does. Without the break statement, there would be an infinite loop because the while statement is looping on true. You need to “break” out of the while loop because looping on true is what creates the infinite loop in the first place. Normally there’s an expression there that will eventually evaluate to false, but since there isn’t, that’s what the break statement is for.

There’s no mistake, the code is exactly as the author (Kyle Simpson) wrote it and is intended to print out the numbers 0 through 9 and then stop. With the modification you’ve suggested, the code won’t print out anything to the console.

Try running it on a new tab, I’m 100% sure this should work on any browser but you know, browsers are known to have inconsistencies.

Another way you can go about it is:

if(!(i <= 9)) {

! stands for NOT (negation). I’m using the latest version of Chromium and I get no infinite loop.

Thank you all for helping me out. I tried it again after rebooting and it worked fine.