14 Tricks to Get JavaScript Debugging

Source: Internet
Author: User
Keywords javascript debugger javascript debugger online js debugger

Mastering the use of tools can greatly improve the efficiency of solving problems. Although JavaScript is known for being difficult to debug, if you know some tricks you can get it done faster. In this article, I have summarized 14 Debug tips, which may be useful to you!

Alibaba Cloud Simple Application Server: Anti COVID-19 SME Enablement Program
$300 coupon package for all new SMEs and a $500 coupon for paying customers.

Most tips are for the Chrome Inspector and Firefox, although many people use other inspectors.

1. debugger;
In addition to console.log, debugger; is my favorite quick debug tool. Once this line of statements is added to the code, Chrome will automatically stop at that line when it executes. You can even use it with conditional statements and only turn it on when you need it.

if (thisThing) {
    debugger;
}

2. Display objects in the form of a table
Sometimes, you need to view a complex object element. Usually, we will use console.log to print it out and view. In fact, you can also use console.table to make objects appear more beautiful.
var animals = [
    { animal: "Horse", name: "Henry", age: 43 },
    { animal: "Dog", name: "Fred", age: 13 },
    { animal: "Cat", name: "Frodo", age: 18 }
];

console.table(animals);
3. Try to adapt the screen size of various models
If you have a variety of mobile phones, the test will be relatively simple, but this is not the case. In fact, you can change the size of the viewport directly in the browser to view the effect. Google Chrome provides very powerful features. In the Google developer panel, click the toogle device mode button, you can choose a different device size.

4. How to quickly find the corresponding DOM element
Construct a DOM element and use it under the console. The Chrome Inspector retains the history of the last 5 DOM elements. The last tag is $0, the penultimate $1, and so on.

If you click on these elements in the order item-4, item-3, item-2, item-1, item-0, then you can access them using $x in the console.

5. Use console.time() and console.timeEnd() to record the time
Knowing the execution time of the code is very useful, especially for debugging time-consuming for loops. You can set multiple timers by defining different names. Let's demonstrate how to operate:
console.time("Timer1");

var items = [];

for (var i = 0; i < 100000; i++) {
    items.push({ index: i });
}

console.timeEnd("Timer1");

6. Get the Stacktrace of a function
You may know a lot of JavaScript frameworks, they can quickly generate a lot of code with one click. The code contains various views and event triggers, and eventually you will want to understand how certain functions are called.

Because JavaScript is not a very structured language, it is sometimes difficult to figure out when and how it happened. At this time, we can use console.trace to debug JavaScript.

For example, if you want to see a Car instance, the entire stack details of funcZ:

Using console.trace, the output is as follows:

We can clearly see that func1 calls func2, func2 calls func4, func4 creates an instance of Car, then calls car.funcX, and so on.

Sometimes, even if you think you are very clear about your code, using console.trace can still help you locate functions quickly. For example, if you want to improve the code, all related functions can be obtained through trace, and each can be clicked to jump directly, just like a shortcut menu.

7. Restore the minify code
Sometimes, there is a problem with the code in the production environment, but the source map is not tied to the compressed code, so the restored code cannot be seen. Don't worry, Google Chrome can restore JavaScript code to a readable style. Although it is still not as good as the real code, it can help you to analyze the problem. Click {} to structure the code:

8. Quickly locate functions that require Debug
Imagine that we want to set a breakpoint in a function. The two most common ways are:

Find this line of code in the inspector and set a breakpoint;
Add debugger to the code
Either way, you need to find the line that needs to be debugged first in all code files.

Another uncommon way is to use the console (console), use debug (funcName), the script will pause at that line of function. Using this method can quickly locate the function, but it is not suitable for private and anonymous functions. (Note: debug and console.debug are not the same thing!)

Enter debug(car.funcY) in the console, and the script will enter debug mode at the function call car.funcY.

9. Block unrelated scripts
Many library functions and frameworks are introduced in our code. Most are tested and there are few bugs. But debugger will accidentally jump in. Therefore, we can choose to block these scripts. You can view the settings of the Google Chrome shield file and the Firefox browser shield file settings.

10. Personalized console.log information
In some very complicated Debug, we need to output many lines of logs, using Console.log, console.debug, console.warn, console.info and console.error. You can use filters to view specific messages, but sometimes you will find that this is not enough. We can use a more creative method to use CSS to personalize the messages printed by Console.log:

The output is as follows:

You can use %s to output strings, %i to output numbers, and %c to customize the format. If you use a single-page framework, use one format for the console message of the view. The model, collection, and controller use different formats. Even, you may want shorter names, similar to wlog, clog and mlog.

11. View a function call and its parameter value
In the Google Chrome console, you can always observe a function. Each time it is called, it will print the incoming parameter value.

Use the monitor function to get the parameter values passed in when the function runs. However, there is a disadvantage in that the number of formal parameters of the function is not specified. So func1 actually requires three parameters, but only two are passed in. If you ignore this situation, it may lead to bugs.

12 Quick access to elements in the console
It is convenient to use the query selector (querySelector) in the console. Using $('css-selector') will return the first matched element, and $$('css-selector') will return all matched elements. If you use an element multiple times, you can even save it to a variable.

13 Postman is good (but Firefox is faster)
Many developers use Postman to send Ajax requests. Postman is very easy to use, but opening a new window and configuring the request object is still a bit tedious.

If you don’t need to worry about using cookie authentication, then you can edit and resend the request in Firefox.

Open the inspector and jump to the network tab. Right-click the selected request and choose Edit and Resend Options.

The following picture is the situation where I edited the attributes of the same GET request and sent it again:

14 Monitor node element changes and interrupt
Sometimes the DOM changes somehow, but you don’t know why. Fortunately, Google Chrome provides a function to pause execution when DOM elements change. Under Google Inspector, right-click the selected element, and then select the type of change to monitor: Subtree Modifications, Attributes Modifications, Node Removal.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.