Search code examples
javascriptv8console.logspidermonkey

Why is my while loop getting logged this way?


Why is my while loop getting logged this way? Is it because the internal workings of V8 and SpiderMonkey differ?

var counter = 0;
while (counter <= 10) {
    console.log(counter);
    counter++;
}

Note: Try the above code in a Chrome and a Firefox console.

These are the results I got while executing the above code.

In Chrome:

In Chrome's Console

In Firefox:

In Firefox's Console

Why are the logged results different? What's going on here?


Solution

  • Yes, the internal workings differ. I believe the difference you are noticing here is actually because in WebKit browsers, like Chrome and Safari, console.log is asynchronous, whereas in Firefox (and Node.js) it is strictly synchronous.

    I first read about this in the book Async JavaScript by Trevor Burnham. You can find the relevant section of the book by going to this Google Books search link for Async JavaScript and the relevant page should be the first response at the top.

    WebKit's console.log has surprised many a developer by behaving asynchronously.

    To help understand what is going on, try simply entering this into the console:

    var counter = 0
    while (counter <= 10) { counter ++ }
    

    You will see that this will naturally return the value of 10 by itself. This is just the final value of counter at the end of the while loop. So, because console.log is synchronous in Firefox, the console.log statements start at the same time that the return value for the while loop, 10, is returned. Because it is asynchronous in Chrome, the while loop's return value waits to return until all the console.log invocations are complete. The difference in the synchronous nature of console.log between Chrome and Firefox is changing whether this value is returned at the same time or after all the console.log calls. That is the essence of the difference you noticed.

    If you are still confused, I recommend reading up on the concept of asynchronous code. It is an intermediate-level concept, so it is OK if you are just starting out and you don't fully grasp it yet. The book quoted above is a great resource, but you can start learning the basics on the Mozilla Developer Network. Here are some resources for you from MDN that serve as primers on asynchronous programming: