preface
You’ll probably use console.log, a debugger, or a debugging tool to debug your code. But most of us use console.log when it’s easy, but can console.log really be trusted?
Conclusion: Console. log is printing reference type data and may be inaccurate. For complex breakpoint debugging, use the Debugger or debugging tool whenever possible.
Console. log is abnormal
var a = {
index: 1,}console.log(a)
a.index++
console.log(a)
Copy the code
The above code runs in three different cases and you’ll find it interesting:
- Node. Js platform
- The situation where the Web console is not opened (note: this refers to opening the console after running the code)
- Open the console on the Web side (note: here refers to open the console to refresh)
Note: The above Web end has been tested by modern browsers and found that chrome, Edge and Firefox have the same performance and are similar to the above. Safari cannot expand the object in the third case.
Abnormal analysis
Why does the Web side behave differently from Node.js
We all know about reference types, and every time we use an object, we’re just using a reference to the object in the heap. This is what we expect to be the case on node.js, but why is it the case on the Web?
As mentioned in javascript You Didn’t Know, the console.* family of methods is not officially part of javascript, but is added to javascript by the host environment. Therefore, different browsers and JavaScript environments can be implemented as they wish.
In most browsers, console.log does not output incoming content immediately, but rather gives it to the browser for asynchronous processing to improve performance.
Node. js platform for synchronous printing, browser platform for asynchronous printing.
Is the Web console open
Console not open
Console. log works in most browsers after the console is opened, that is, when you open the console, it prints.
In the above code, the parameter passed to console.log is an address, and when the code is finished, it opens the console and starts printing, and it actually prints out the object that has been processed. This is equivalent to this order of execution:
var a = {
index: 1,
}
a.index++
console.log(a)
console.log(a)
Copy the code
Open the console
If you open the console and run the code (that is, open the console and refresh), console.log is directly in action. The browser has a snapshot technology, so we can see that what we see on the console is the correct result. But the object that corresponds to our address is still what it ended up looking like, so it expands differently.
The solution
Deep copy (not recommended)
console.log(JSON.parse(JSON.stringify(a)));
Copy the code
Make a deep copy of the current object and output it again.
After a deep copy, it no longer points to the same heap.
Debugger or debugging tool
Using a debugger or debugging tool can help you avoid errors and should be used frequently in your daily work.