How Console.log Changes Hoisting in JavaScript

The big surprise here is that console.log doesn’t actually change hoisting in JavaScript. If you are looking for an introduction to JavaScript hoisting I recommend you first read this blog post. If you are having an issue where it looks like console.log might be changing the hoisting order of your program, it is most likely due to a Chrome a bug. Although this bug was first reported in March 2010 and was patched by WebKit in August 2012, it still has not been integrated with Google Chrome. Here’s a description of that bug on WebKit Bugzila:

1) create an object literal with one or more properties 2) console.log that object but leave it closed (don't expand it in the console)
3) change one of the properties to a new value

Now, open that console.log and you'll see that it has the new value for some reason, even though its value was different than it was at the time it was generated.

In order to replicate this problem create the following HTML file:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

And then create the following JavaScript file:

var A = [2, 1];
var C = A;
console.log(C);
A.sort();
console.log(C);

Now open the JavaScript file and open the console. If you expand the arrays you’ll see the following:

example

Notice that both arrays are sorted despite the A.Sort() function having been run after the first array was declared. If you come across something like this you would assume that the reason is that the console.log somehow changed the hoisting order and that the array got sorted before it was logged out.

This interesting behavior becomes easier to understand if you hover over the “I” next to the array. As you can see, the following statement came up: “Object state below is captured upon first expansion.” What this means is that until it’s expanded these objects are actually object references and not actual textual representations of the objects.

arrow

If you refresh the page now, the console actually just prints out a textual representation of the arrays. They do print out correctly.

string

You should also be aware that if you are using tests which try to emulate a browser you might run into similar issues. The solution is fairly simple: just comment out the console.log statement.

Paulo Diniz