background

When fixing a bug, I often use console.log to see what the problem is. But when I print an object, I often have to use json.stringify to print the value of the object at that point in time.

Such as:

let object = {a: 1}
console.log(object)
object.a++
Copy the code

What is the result of the execution?

In Chrome, the I on a light blue background told me: Value below was Evaluated just now.

I used to think that the root cause of this phenomenon was that the object was a reference. It never occurred to me that the problem might be with console.log as well.

console.log

https://developer.mozilla.org/zh-CN/docs/Web/API/Console/log
Copy the code

As you can see from the documentation, console.log does not belong to any public specification. In fact, not only console.log, but console.* as a whole, there is no specification that specifies how they work.

That is, console.* is not an official part of javascript, but is added to it by the host environment.

Therefore, different browsers and javascript environments can be implemented as they wish.

In some browsers, console.log does not immediately output incoming content. Because in many languages, I/O is a very slow blocking part. So browsers choose to process console I/O asynchronously in the background to improve performance. So the user doesn’t realize it’s an asynchronous behavior at all…

supplement

It is uncertain when browser console I/O will be delayed, and if you see unexpected results when an object is modified after the console.log statement during debugging, be aware that this may be due to asynchrony of the I/O.

Solution:

  • Debugging with breakpoints
  • Serialize the object to a string for output