- create an object literal with one or more properties
- console.log that object but leave it closed (don't expand it in the console)
- 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>
var A = [2, 1]; var C = A; console.log(C); A.sort(); console.log(C);
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.
If you refresh the page now, the console actually just prints out a textual representation of the arrays. They do print out correctly.
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.