14 Strokes to fix JavaScript debugging

Source: Internet
Author: User

14 Strokes to fix JavaScript debugging

Translator by: many times, you may just rely on Console.log to debug JavaScript code, the limitations of this is self-evident, this blog will teach you a few practical debugging skills.

    • Original: The debugging tips you probably didn ' t know)
    • Translator: Fundebug

In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.

Mastering the use of tools can greatly improve the efficiency of the problem-solving process. Although JavaScript is known to be difficult to debug, if you know some tricks you can get it done faster. This article I summed up 14 debugging tips, may be useful for you!

Most of the tricks are for the Chrome Checker (Inspector) and Firefox, although a lot of people use other inspectors.

1.  debugger;

Besides console.log , debugger; it's my favorite tool for quick Debug. Once the line has been added to the code, Chrome will automatically stop at that line when it executes. You can even use the conditional statement to open it only when you need it.

if (thisthing) {debugger;}
2. Display the object in a tabular format

Sometimes you need to look at a complex object element. Usually, we'll use console.log it to print it out and look at it. In fact, you can also use console.table , make the object more beautiful to present.

var animals = [{ animal: ' Horse ', name: ' Henry ', age : + }, { Animal: ' Dog ', name: ' Fred ', age : + },{  Animal: ' Cat ', name: ' Frodo ', age : + }]; console.table (animals);

Output style:


3. Try to fit a variety of models screen size

If you have a variety of mobile phones then the test will be relatively simple, but the reality is not. In fact, you can change the size of the viewport directly in the browser to see the effect. Google Chrome offers a very powerful feature. On the Google Developer panel, click on the toogle device mode button to choose a different device size.


4. How to quickly find the corresponding DOM element

Constructs a DOM element and then uses it under the console. The Google Browser debugger (Chrome Inspector) retains the history of the last 5 DOM elements. The last mark is $ A, the second from the bottom, and so on.

If you follow,,, and item-4 item-3 click on item-2 item-1 item-0 These elements in the order, then you can use them under the console $x to access them.


5. Use Console.time () and Console.timeend () to record time

It is useful to understand the execution time of the code, especially when debugging a time-consuming for loop. You can set up multiple timer by defining a different name. Let's demonstrate how to do this:

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 probably know a lot of javascript frameworks that can quickly generate a lot of code with one click. The code contains various view and event triggers, and eventually you will want to figure out how some functions are called.

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

For example, if you want to see the entire stack details under a car instance 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 (' Trace car ')}}func1 ();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 (' Trace car ')}} func1 ();

Use console.trace , the output is as follows:


We can see clearly that func1 called func2,func2 called func4, func4 created an Car instance, and then called the Car.funcx, wait.

Sometimes, although you think your code is very clear, use console.trace can still help you locate functions quickly. For example, if you want to improve the code, you can get all the relevant functions through trace, and each one can click to jump directly, just like a shortcut menu.

Advertising: If you need to monitor online JavaScript code errors, please use fundebug! free of charge .

7. Restore the Minify code

Sometimes there is a problem with the code in the production environment, but the source map does not bind to the compressed code, and all the code that cannot be seen is restored. Don't worry, Google Chrome can restore JavaScript code to a readable style. It's not as good as the real code, but it's a great way to help you analyze the problem. Click {} to structure the code:


8. Quickly locate the function that requires debug

Imagine that we want to set a breakpoint in a function, the two most common ways are:

    1. Find this line of code in the inspector and set the breakpoint;
    2. Add Debugger in your code

Either way, you need to first find the line in all the code files that needs to be debug.

Another uncommon way is to use the console, where the debug(funcName) script pauses at the line function. The function can be positioned quickly using this method, but not for private and anonymous functions. (Note: Debug and console.debug are not the same thing!) )

var func1 = function () { func2 ();}; var Car = function () { this.funcx = function () { This.funcy (); } this.funcy = function () { This.funcz (); }} var car = new car ();

In console input debug(car.funcY) , the script enters debug mode at the function call car.funcY .


9. Masking unrelated scripts

Many library functions and frameworks are introduced into our code. Most are tested, with little or no bugs. But debugger would accidentally jump in. Therefore, we can choose to block these scripts. You can view the settings of the Google Chrome screen file and the Firefox screen file settings.

10. Personalized Console.log Information

In some very complex debugs, 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'll find that's not enough. We can use a more creative approach, using CSS to personalize the Console.log printed message:

Console.todo = function (msg) { console.log ('% c% s% s% s ', ' color:yellow; background- Color:black; ', '-', MSG, '-');} console.important = function (msg) { console.log ('% c% s% s% s ', ' color:brown; font- Weight:bold; text-decoration:underline; ', '-', MSG, '-');} Console.todo ("This was something that's need to be fixed"); console.important (' This was an important message ');

The results of the output are as follows:


You can use%s to output a string,%i to output a number, and%c to customize the format. If you use a single-page frame, the console message for the view is used in one format, model, and collection, and the controller uses a different format for each. Even, you may want shorter names, similar to Wlog, clog and Mlog.

11. View a function call and its parameter values

In the Google Chrome console, you can always watch a function. Each time it is called, the incoming parameter value is printed.

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

Use monitor a function to get the value of the parameter passed in when the function is run. However, one disadvantage is that it does not indicate the number of formal parameters for the function. So we func1 actually need three parameters, but only two are passed in. If this is omitted, a bug may occur.

12 quick access to elements in the console

It is convenient to use the query selector (queryselector) in the console to $(‘css-selector‘) return the first matching element and $$(‘css-selector‘) return all matching elements. If you use an element multiple times, you can even save it to a variable.


Postman is good (but Firefox is faster)

Many developers use postman to send AJAX requests. Postman is very useful, but opening a new window and configuring the Request object is a bit cumbersome.

If you don't need to worry about using cookie authentication, you can edit and re-send requests in Firefox.

Open the inspector and jump to the Network tab. Right-click on the selected request and select Edit and re-send options.

Is the case where I have edited the property of the same get request and sent it again:


14 Monitoring node element changes and interrupts

Sometimes the DOM somehow changes, but you don't know why. Fortunately, Google Chrome provides a feature that pauses execution when DOM elements change. Under Google Inspector, right-click the selected element and select the type of change you want to monitor: subtree modifications, Attributes modifications, Node removal.





Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2017/11/08/14-javascript-debugging-tips/ 

Does your user encounter a bug?

14 Strokes to fix JavaScript debugging

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.