Debug JavaScript faster and more efficiently

Being familiar with tools can make them more useful at work. Despite rumors that JavaScript is hard to debug, if you master a few tricks, you can fix bugs and bugs in a fraction of the time.

This article has listed 14 debugging tips that you may not know, but might want to keep in mind for the next time you need to debug JavaScript code!

See together

Most of these tips work for the Chrome console and Firefox, and while there are plenty of other debugging tools out there, most work as well.

1. debugger

Besides console.log, debugger is our favorite fast and dirty debugging tool. After executing the code, Chrome automatically stops while executing. You can even encapsulate it as a condition that runs only when needed.

if (thisThing) {
    debugger;
}
Copy the code

2. Display objects in a table

Sometimes, you have a complex set of objects to look at. You can view and scroll through console.log, or use console.table to expand and 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);
Copy the code

Output:

3. Use different screen sizes

It’s great to have different mobile device emulators on your desktop, but it’s not practical. How do I resize my window? Chrome provides everything you need. Jump to the console and click the ‘Switch Device Mode’ button. Observe window changes can!

4. How to find DOM elements quickly

Mark a DOM element in the Elements panel and use it in the console. The Chrome console keeps the last five elements of the selection history, with the first selected element marked $0, the second selected element marked $1, and so on.

DOM nodes can be accessed in the console if you select the following tags in the order of “item-4”, “item-3”, “item-2”, “item-1”, and “item-0” :

5. Useconsole.time()console.timeEnd()The test cycle

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

console.time('Timer1');

var items = [];

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

console.timeEnd('Timer1');
Copy the code

The run yields the following results:

6. Get the stack trace information for the function

Using a JavaScript framework introduces a lot of code.

You create the view and fire the event, and finally you want to understand the process of the function call.

Because JavaScript is not a very structured language, it’s sometimes hard to know when something is going on. You can easily debug JavaScript using console.trace (which is just tracing in the console).

Imagine looking at the entire stack trace for the car instance calling function funcZ on line 24:

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(); FuncZ = function() {console.trace(' trace car ')}} func1();Copy the code

Line 24 will print:

You can see that func1 calls func2 and func2 calls func4. Func4 creates an instance of Car, then calls the function Car. FuncX, and so on.

Even if you think your code is great, this is still useful. Let’s say you want to improve your code. Get trace information and all the functions involved, each of which can be clicked, and you can switch back and forth between them. It’s like giving you a list of call stacks to choose from.

7. Format the code before debugging JavaScript

Sometimes code breaks in production, but your Source Maps are not deployed in production. Don’t be afraid. Chrome formats your JavaScript files. The formatted code isn’t as useful as the real thing, but at least you can 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 a point in a function, the two most common ways are:

  1. Look for rows in the console and add breakpoints
  2. Add in the codedebugger

In both solutions, you have to click in the file to debug a particular line.

Using console interrupt points may not be common. Use Debug (funcName) in the console to stop the code when the incoming function is reached.

This debugging method is quick, but the downside is that it does not work with private or anonymous functions. But with the exception of private and anonymous functions, this is probably the fastest way to find debugging functions. (Note: this function is not the same as the console.debug function.)

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

var Car = function() {
  this.funcX = function() {
    this.funcY();
  }

  this.funcY = function() {
    this.funcZ();
  }
}

var car = new Car();
Copy the code

Type DEBUG (car.funcy) in the console, and when car. FuncY is called, it stops in debug mode:

9. Block irrelevant code

Nowadays, we often introduce several libraries or frameworks into our applications. Most of them are well tested and relatively bug free. However, the debugger still enters files that are not relevant to the debugging task. The solution is to mask scripts that don’t need debugging. Include your own scripts, of course.In this article to read more about debugging unrelated code (https://raygun.com/blog/javascript-debugging-with-black-box/)

10. Focus on complex debugging

In more complex debugging, we sometimes want to output many lines. What you can do is keep the output structure nice and use more console functions, such as console.log, console.debug, console.warn, console.info, console.error, etc. You can then quickly browse in 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 console information:

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 is something that's need to be fixed "); Console. important(' This is an important message ');Copy the code

Output:

Such as:

In console.log(), you can use %s to set strings, % I to set numbers, %c to set custom styles, etc., and there are many better ways to use console.log(). If you are using a single-page application framework, you can create one style for view messages and another style for Models, Collections, controllers, and so on. Maybe use your imagination like Wlog, CLOG and Mlog!

11. Observe calls and arguments to specific functions

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

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

Output:

This is a good way to see the parameters of the function passed in. However, it would have been nice if the console had prompted us for the number of parameters. In the example above, Func1 expects three arguments, but only two are passed in. If you do not handle this parameter in your code, you are likely to make an error.

12. Quick access to elements in the console

The faster method in the console than querySelector is to use the dollar sign, where $(‘ CSS-selector ‘) will return the first match of the CSS selector. ? (‘css-selector’) will return all matches. If you use an element multiple times, you can save it as a variable.

13. Postman is Great (But Firefox is faster)

Many developers use Postman to view Ajax requests. Postman is really good. But opening a new window, writing request objects, and then testing them is cumbersome.

Sometimes it’s easier to use a browser.

You don’t need to worry about authentication cookies if you request a password authentication page when viewing with your browser. Here’s how to edit and resend a request in Firefox.

Open the console and switch to the Network TAB. Right – click the request you want, then select Edit and resend. Now you can change anything you want. Change the title and edit the parameters, then click Resend.

Here are two requests I made with different attributes:

14. Interrupt 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 on the element and select Interrupt in Settings: