14 JavaScript Debugging Tips you may not know

Source: Internet
Author: User
Tags stack trace

Ext: Https://mp.weixin.qq.com/s/Hmrk6JWEbz8gb6uqEnDcDQ

Familiarity with tools allows tools to play a greater role in the work. JavaScript is hard to debug, though, but if you have a few tricks, you can use less time to solve errors and bugs.

There are 14 debugging tips that you may not know about, but you may need to keep them in mind so that you can use them the next time you need to debug JavaScript code.

Together to see

Most of the techniques apply to chrome consoles and Firefox, although there are many other debugging tools, but most of them are also available. 1. Debugger

In addition to Console.log, debugger is our favorite, Fast and dirty debugging tool. After the code is executed, Chrome stops automatically when it is executed. You can even encapsulate it as a condition and run it only when it is needed.

if (thisthing) {
 debugger;
}
2. Display objects in a table

Sometimes, there is a complex set of objects to view. You can view and scroll through the Console.log, or use console.table to expand and make it easier to see what you're working on.

var animals = [
 {animal: ' horse ', Name: ' Henry ', age:43},
 {animal: ' Dog ', Name: ' Fred ', age:13},
 {animal: ' Cat ', Name: ' Frodo ', age:18}
];

Console.table (animals);

Output:

3. Use different screen sizes

It's great to install different mobile device simulators on your desktop, but reality is not feasible. How to resize the window. Chrome provides everything you need. Skip to the console and click the ' Switch Device mode ' button. Watch the window change!

4. How to quickly find DOM elements

Mark a DOM element in the elements panel and use it in the console. The chrome console retains the last five elements of the selection history, the first element of the final selection is marked as $, the second selected element is $, and so on.

If you select the following labels in the order of "item-4", "item-3", "Item-2", "item-1", "item-0", you can access the DOM node in the console:

5. Use Console.time () and console.timeend () test loops

It is useful to know the execution time of some code, especially when debugging a slow loop. You can even set multiple timers by passing in different parameters to the method. Let's see how it works:

Console.time (' Timer1 ');

var items = [];

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

Console.timeend (' Timer1 ');

Run produces a result:

6. Get the stack trace information for the function

With the JavaScript framework, a lot of code is introduced.

Create the view and trigger the event, and finally you want to know the procedure for the function call.

Since JavaScript is not a very structured language, it is sometimes difficult to know when something is going on. You can easily debug JavaScript by using Console.trace (just tracking in the console).

Imagine that you want to view the entire stack trace information for the 24th line car instance calling function Funcz:

var car;
var func1 = function () {
 func2 ();
}

var func2 = function () {
 func4 ();
}
var func3 = function () {
}

var func4 = function () {Car
 = new car ();
 car.funcx ();
}
var car = function () {
 This.brand = ' Volvo ';
 this.color = ' red ';
 this.funcx = function () {this
 . Funcy ();
 }

 this.funcy = function () {
 This.funcz ();
 }

 This.funcz = function () {
 console.trace (' tra Ce car '
 }}
func1 ();

24 Row output:

You can see func1 call Func2, Func2 call Func4. Func4 creates an instance of car and then calls the function Car.funcx, and so on.

Even if you think your code is very good, it's still useful. If you want to improve your code. Get the tracking information and all the functions involved, each item can be clicked and can be switched back and forth between them. It's like giving you a select list of call stacks. 7. Format the code before debugging JavaScript

Sometimes the code will go wrong in the production environment, but your source maps is not deployed in the production environment. Don't be afraid. Chrome can format your JavaScript files. The formatted code, while not as useful as the real code, can at least see what's going on. Click the {} button in the source Viewer in the Chrome console.

8. Quickly find the function to debug

Suppose you want to break points in a function, two of the most common ways are:

Find rows in the console and add breakpoints

Add Debugger to Code

In both of these solutions, you must click in the file to debug a specific row.

Using a console interrupt point may not be common. Using Debug (FuncName) in the console, the code stops when the incoming function is reached.

This debugging method is quick, but the disadvantage is that it does not apply to private or anonymous functions. But in addition to private and anonymous functions, this may be the quickest way to find a debug function. (Note: This function is not the same thing as the Console.debug function.) )

var func1 = function () {
 func2 ();
};

var car = function () {
 this.funcx = function () {
 this.funcy ();
 }

 this.funcy = function () {
 th Is.funcz ();
 }

var car = new car ();

In the console, enter debug (car.funcy), which will stop in debug mode when Car.funcy is invoked:

9. Shielding irrelevant code

Now, we often introduce several libraries or frameworks into the application. Most of them are well tested and relatively free of defects. However, the debugger still enters files that are not related to the debugging task. The solution is to mask scripts that do not require debugging. Of course, you can include your own script. Read more about debugging unrelated code in this article (https://raygun.com/blog/javascript-debugging-with-black-box/)

10. Find the key in the complex debugging process

In more complex debugging, we sometimes want to output a lot of rows. What you can do is keep a good output structure and use more console functions, such as:

Console.log, Console.debug, Console.warn, Console.info, Console.error and so on. You can then quickly browse through the console. Sometimes, however, some Javascrip debugging information is not what you need. Now, you can beautify the debugging information yourself. When debugging JavaScript, you can use CSS and customize the console information:

Console.todo = function (msg) {
 console.log ('% c% s% s ', ' color:yellow; background-color:black; ', '-', MSG, ' – ');

Console.important = function (msg) {
 console.log ('% c% s% s ', ' Color:brown; font-weight:bold; Text-decora Tion:underline ', ' – ', MSG, ' – ');

Console.todo ("This is something so ' need to be fixed");
Console.important (' This is a important message ');

Output:

For example:

In Console.log (), you can set a string with%s,%i set numbers,%c to set custom styles, and so on, and there are many better ways to use Console.log (). If you are using a single-page application framework, you can create a style for the view message, create another style for the model (models), the collection (collections), the controller (controllers), and so on. It may also be as imaginative as Wlog,clog and Mlog. 11. Observe the invocation and parameters of a particular function

In the chrome console, you can observe specific functions. Each time the function is called, the incoming arguments are printed out.

var func1 = function (x, y, z) {
//...
};

Output:

This is a good way to view incoming function arguments. However, it is even better if the console prompts us for the number of formal parameters. In the above example, the FUNC1 expects 3 parameters, but only 2 parameters are passed in. If you do not handle this parameter in your code, you are likely to have an error. 12. Quick access to elements in the console

A faster way to console than Queryselector is to use the dollar sign, $ (' css-selector ') to return the first occurrence of the CSS selector. $$ (' Css-selector ') will return all occurrences. If you use an element more than once, you can save it as a variable.

postman is great (but Firefox is faster)

Many developers use postman to view Ajax requests. Postman is really excellent. But it's cumbersome to open a new window, write the request objects, and then test them.

Sometimes it's easier to use a browser.

When you use a browser to view, if you request a Password Authentication page, you do not need to worry about the authentication cookie. See below, how to edit and resend the request in Firefox.

Open the console and switch to the Network tab. Right-click the desired request, and then select Edit and Resend. Now you can change whatever you want. Change the caption and edit the parameters, and then click Resend.

The following two requests I have initiated with different attributes:

14. Break Node Changes

Dom is an interesting thing. Sometimes it changes, and you don't know why. However, when you debug JavaScript, chrome can pause when a DOM element changes. You can even monitor its properties. In the Chrome console, right-click the element, and then select interrupts in the settings:

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.