How to debug a JavaScript application. Variable Hints


From the author: console.log can tell you a lot about your application, but it doesn't allow you to truly debug your code. The new JS debugger in Firefox will help you write code faster and without bugs. An article about the operating principle of this debugger.

In this example, we will open a very simple application that makes JavaScript debugging easy. The application itself runs on basic open source JS frameworks. Open it in latest version Firefox Developer Edition and run debugger.html using the combination Option keys+ Cmd + S on Mac or Shift + Ctrl + S on Windows. The debugger is divided into 3 panels: a file list panel, a code panel, and a toolbar.

The toolbar is divided into toolbar, watch expressions, breakpoints, call stack and areas.

Stop using console.log

We want to use console.log to debug our code. We just add a call to the code to find out the value of the variable, and that’s it, right? This approach will work, but it is cumbersome and time-consuming. In this example, we will step through the application using debugger.html to find the value of a variable.

With debugger.html you can dive deeper into your code by simply adding a breakpoint on a line. Breakpoints pause the debugger so you can look at the code. In this example, we will add a breakpoint on line 13 of the app.js file.

Now add the task to the list. The code will stop at the addTodo function, and we can look at the value of the field in the code. Hover over a variable to see its value, etc. This way you can see anchors, applets, child elements etc.:

The same information can be found in the Areas panel.

When the script is paused, you can execute its lines step by step using the toolbar. The Resume/Pause buttons do exactly what they say. The Step Over button performs current line code, Enter – goes inside the function, Exit – executes the current function before exiting its call.

Monitor the value of a mono variable also using watch expressions. Simply enter an expression in the Expressions to Watch box and the debugger will watch for it as your code runs. In the example above, you can add title and to-do expressions and the debugger will break down the values ​​when they are available. Especially useful when:

You step through the code and watch the value change;

You debug the same code many times and want to see general values;

You're trying to figure out why that damn button isn't working.

You can also debug React/Redux applications using debugger.html. How it works:

Navigate to the component you want to debug.

See the component diagram on the left (functions in a class).

Add breakpoints to appropriate functions.

Press pause and observe the properties and states of the component.

The call stack is simplified, so you see application code mixed with the framework.

debugger.html allows you to look at confusing or minified code that may cause errors. Especially useful when working with common frameworks like React/Redux. The debugger knows about the component you paused on and will show a simplified call stack, component diagram, and properties. Below, developer Amit Zur explains how he uses the Firefox code debugger on JS Kongress:

If you'd like to take a closer look at the new debugger.html, check out the Mozilla Developer Playground. We've created a series of tutorials to help developers learn how to effectively use the tool to debug code.

Open Source Developer Tools

The debugger.html project was launched approximately 2 years ago along with a complete overhaul of Firefox DevTools. We wanted to move DevTools to modern technologies, open them to developers around the world. And because the technology is open, it can freely grow into something the small group at Mozilla could never have imagined.

JS is the foundation of any advanced web application, so a powerful debugger was a core part of the toolkit. We wanted to create something fast, easy to use, adaptable - able to debug any new JS framework. We decided to use popular web technologies because we wanted to work closer to the community. This approach would improve the debugger itself - if we adopted Webpack and started using the build tool and source maps internally, we would want to improve source mapping and hot reloading.

debugger.html is written in React, Redux and Babel. React components are lightweight, testable, and easy to design. For rapid UI prototyping and documentation of common components, we use React Storybook. This makes it easier to work with different JS frameworks (such as React). Babel front-end allows you to do things like display the Component class and its functions in the left sidebar. We can also set breakpoints on functions and they won't move if you change the code.

Redux actions are a pure UI API. However, they can also be used to create an independent JS Debugger CLI. The Redux repository has selectors to query the current debugging state. Our unit tests run Redux actions and simulate browser responses. Integration tests bring the browser into action with Redux debugger actions. Herself functional architecture designed for testing.

We've relied on the Mozilla developer community every step of the way. The project was published on GitHub, and our team reached out to developers around the world, and they responded. At the very beginning, automated tests were critical to the community. The tests performed regression and documented behavior that could easily be overlooked. That’s why one of the first steps was to write unit tests for Redux actions and Flow types for the Redux store. In fact, the community ensured that Flow and Jest coverage helped ensure that every file was written and tested.

As developers, we believe that tools are stronger the more developers are involved. Our core team It was always small (2 people), but on average there were 15 assistants per week. The community gave us different perspectives, which helped us anticipate challenges and write features we never imagined. We are currently formatting call stacks for 24 libraries. We didn't even know about many of them. We also show Webpack and Angular maps in the source tree.

We plan to move all Firefox DevTools to GitHub so they can be used and improved more people. We will gladly accept your help. You can go to our project page debugger.html on GitHub. We've written a whole list of instructions for running the debugger on your machine, where you can change whatever you want. Use it to debug JS code for anything - browsers, terminals, servers, phones, robots. If you see something that can be improved, write to us on GitHub.

When it comes to finding the cause of errors, knowing your tool can make all the difference. Even though JavaScript has a reputation for being difficult to debug, if you know a few tricks, it will take less time to find the cause of the error.

We've compiled a list of 14 debugging tips, which you might not know about, but which can help you debug JavaScript code.

Most of these tips are for Chrome and Firefox, although most of them work in development tools for other browsers.

1. 'debugger;'

After console.log, ‘debugger;‘ my favorite quick and dirty debugging tool. Once you add it to your code, Chrome automatically stops code execution at that point. You can even wrap it in a condition so that it only fires when you need it.

If (thisThing) (debugger; )

2. Displaying objects as tables

Sometimes you have a complex set of objects that you want to view. you can use console.log to display them, and then scroll through a huge list, or use console.table. This makes it much easier to understand what you are dealing with.

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 watching at different resolutions

It would be amazing if there was any mobile device, however, in the real world this is not possible. How to resize the viewport? Chrome gives you everything you need. Go to Developer Tools and then click on the Switch Device Mode button. See your media expressions come to life!

4. Quickly search for DOM elements

Select a DOM element in the Toolbox, and then access it in the console. Chrome's dev tools remember the last five elements: the last selected element $0, the second to last selected element $1, etc.

If you selected the following elements in the order 'item-4', 'item-3', 'item-2', 'item-1', 'item-0', then you can access DOM elements as shown in consoles:

5. Measuring code execution time using console.time() and console.timeEnd()

It can be very useful to know how long a piece of code takes to execute, especially when debugging slow loops. You can set multiple named timers. Let's see an example:

Console.time("Timer1"); var items = ; for(var i = 0; i< 100000; i++){ items.push({index: i}); } console.timeEnd("Timer1");

This code will produce the following result:

6. Obtaining a stack trace for a function

You probably know that JavaScript frameworks contain a lot of code.

This code renders the interface, fires events, so eventually you'll want to know what caused the function to be called.

Since JavaScript is not a highly structured language, it is sometimes useful to get information about what happened and when. At this moment he comes on stage console.trace.

Imagine you want to see the entire call stack for a function funcZ in copy car on line 33.

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();

Now we see that func1 causes func2, which causes func4. Func4 creates an instance Car and then calls the function car.funcX, etc.

Even if you think you know the program execution script well, this can be very convenient. Let's say you want to improve your code. Get a stack trace and a list of all associated functions, each of which is viewable.

7. Formatting minified code

Sometimes you may encounter a problem right in production, but your source maps are not on the server. It's OK. Chrome can format your JavaScript files to make them more readable format. Of course, the code will not be as informative as source, but on at least, You can understand what is happening in it. Click the button {} « Pretty Print", located under the code viewer in the inspector.

8. Quickly debug a function

Let's say you want to add a breakpoint to a function.

There are two most common ways to do this:

  1. Find the desired line in the inspector and add a breakpoint
  2. Add debugger to your script

Both of these solutions require searching the desired file And the desired line, which you want to debug.

Using a console for this purpose is probably less common. Use debug(funcName) in the console, and the script will pause when it reaches the desired function.

This is very quick way however it does not work on private and anonymous functions. But if your situation is different, then this is probably the fastest way to debug the function. (Author's note: there is a function console.debug, which is needed for another.)

Var func1 = function() ( func2(); ); var Car = function() ( this.funcX = function() ( this.funcY(); ) this.funcY = function() ( this.funcZ(); ) ) var car = new Car();


9. Scripts that do not require debugging

10. Find important things with more advanced debugging techniques

More complex debugging scenarios may require many lines of output. One way to structure the output data is to use various functions console. For example, console.log, console.debug, console.warn, console.info, console.error, etc. You can then filter them in the inspector. But sometimes this is not exactly what you need when debugging. Now you can be creative and create own formats outputting data to the console using CSS.

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’);


11. Track function calls and function arguments.

IN Chrome console, You can monitor certain functions. Every time a function is called, it will be logged along with the parameters passed to it.

Var func1 = function(x, y, z) ( //.... );

This great way see with what arguments the function is called. But I have to say that it would be nice if the console could determine how many arguments to expect. In the above example func1 expects three arguments, but only two are passed. If this is not handled in code, it may result in an error.

12. Quick access to elements in the console

A faster way to use querySelector in the console is to use $. $('css-selector') will return the first matching element, and $$('css-selector') will return all matching elements. If you use an element more than once, you can save it to a variable.

13. Postman is great (but Firefox is faster)

Many developers use Postman to test AJAX requests.

Sometimes it is easier to use a browser for these purposes.

When you no longer worry about login cookies if you are working on a password protected page. Here's how you can edit and resend requests in Firefox.

Open the inspector and go to the Network tab. Right-click on the request you are interested in, and then select “Edit” and “Resend.” Now you can change anything: correct the title, edit the parameters and click “Resend”.

Below I have given an example of a request that was sent several times with different parameters:

14. Breakpoint when a DOM element changes

The DOM can be funny. Sometimes, elements in it change for reasons unknown to you. However, when you need to debug JavaScript, Chrome allows you to pause code execution when a DOM element changes. Right-click on the element of interest in the inspector, and select a condition to stop execution.

This article will be useful to web developers who are starting to work with JavaScript language and become familiar with the development tools built into the browser. The ability to “debug” a JavaScript application is very important for a web developer, as it allows you to quickly find the cause of an error in a script.

Debugging in Google Chrome

Debugging the application- the process of detecting, localizing and eliminating errors using a debugger (a tool built into the development environment or other software). When debugging, the developer can learn the values ​​of variables and the progress of the program.

In all modern browsers There are tools that allow a developer to analyze the operation of a web application, including executing JavaScript debugging code. To open web developer tools, most browsers use the F12 key. This article will cover debugging JavaScript applications using the example of the Web Inspector tool in Google browser Chrome.

Below is the HTML code of the page with a simple script that will be parsed with using the Web Inspector.

< div id="myDiv"> div>

< script>

Var div = document.getElementById("mydiv");

vartext ="" ;

for ( vari = 0; i< 10; i++)

Text += i +" " ;

Div.innerHTML = text;

< script>

The goal of this script is to create a series of numbers from 0 to 9 and display them in div element On the page. But the code does not work, and we will try to find the problem by debugging.

Launch Web Inspector and switch to the debugger window.

By pressing the F12 key, we get the following window in Google Chrome.

Make sure that the Sources menu item is selected, which allows you to debug.

The debugging window is divided into three panels (marked with numbers in the image):

1 - Panel of files connected to current page, which contain JavaScript code.

2 - Panel in which the JavaScript code of the selected file will be displayed.

3 - Panel with additional settings, simplifying debugging.

Setting a breakpoint or breakpoint

In order to begin debugging the application, you need to determine at what stage the script execution will stop. To do this, as with most other debugging tools, you need to set a breakpoint or breakpoint.

Breakpoint) - a mark that tells the debugger at what point in the application's execution to pause.

First, you need to select the file in which JavaScript debugging will be performed (to do this, double-click on the index.html file)

After that, set a breakpoint by clicking on the line number in the central panel, which displays the code of the selected file. The breakpoint is shown as a blue rectangle. Now, if you refresh the page, the script should run to line 9 and stop. Next, we can step-by-step debug the application and monitor the values ​​of the variables in the script.

One of the advantages of the debugger is the display of errors thrown by the interpreter. On line 14, the message is displayed - Uncaught TypeError: Cannot set property 'innerHTML' of null. This post may already help in solving the script problem. The script tries to access a property on a div variable - the message says that in this null variable and null cannot be set to property values. If the variable contains null, then you need to look for the code that writes the value to the variable.

Step-by-step JavaScript debugging

After installing the breakpoint, you need to start debugging. To do this, just refresh the page (F5). If there was a breakpoint, the script stopped at line No. 9 (this is indicated by the blue highlighting of the line).

While talking with my colleagues recently, I was surprised that many of them had never used the browser's built-in JavaScript console debugger in their work. Unfortunately, one of them works in my company; I will not disclose his name.
For those of you who are not yet familiar with the API browser console, this article is written.

Visual Debugging

When working on a website, debugging mainly relies on visual perception. It is extremely easy to see incorrectly aligned columns, overlapping text, make the necessary edits and refresh the page. For PHP message an error message stops the script and displays the problem directly on the page. In short: most errors that can be fixed immediately are easy to see after the page loads.

The API console is an object (console) that can be used to output debugging information (it can be used once the page has been loaded by the browser). The console is most effective when working with JavaScript.

Debugging javascript firebug

How to track events

Firefox - Log Events

Firefox + Firebug + Firequery = Shows events triggered using jQuery

Brakes - turn off when not working

In the past few years, thanks to the emergence of various libraries such as jQuery and Prototype, JavaScript has gained a leading position among languages ​​for creating scripts for web projects. The growing popularity and ease of use has led to the emergence of full-fledged applications, such as Gmail, which contain thousands of JavaScript strings, placing increased demands on the development team regarding the level of tool proficiency.

The result of increasing application complexity is the need for powerful tools debugging tools that allow you to quickly and efficiently find the source of the error. Simple output of variable values ​​using a function alert() lost its relevance.

This lesson is about short review opportunities modern instruments developers who help make debugging JavaScript code more simple process. The focus will be on the capabilities of the Chrome browser and the Firebug add-on for FireFox, but most of the features described are also available in other tools, such as Dragonfly for Opera.

Console - general view

In most developer programs, the most best friend The programmer will have a console. Multi-purpose panel used for logging error messages, DOM inspection, debugging JavaScript code and many other tasks. Depending on the browser, the console is called by different commands (except direct selection through the menu):

  • V Chrome browser and Dragonfly for Opera - Ctrl + Shift + I
  • Firebug - F12

The console automatically displays errors in the code that are detected during script execution. The file and line are listed next to the error, and clicking on the error moves the input focus to the appropriate location.

We output the data to the console

The console can not only show errors in the script code. Using the Console API and Command Line API, you can control the output of data to the console. The most famous and useful command .log().

When developing form code, it is very useful to know the values ​​of the variables so you can verify that the code is working correctly. A common practice is to use the function alert() for visual inspection. However, using this method blocks the rest of the code from executing until the button in the dialog box is clicked.

A modern solution is to use the method console.log, which outputs variable values ​​to the console panel:

Console.log(“Captain’s Log”); // displays “Captain’s Log” in the console panel

The method can be used to output calculated values:

Function calcPhotos() ( total_photos_diff = total_photos - prev_total_photos; // Print variable values ​​to the console console.log(total_photos_diff); )

The advantage of this approach compared to the method of using dialogue alert() is that code execution is not interrupted, and the developer can print variable values ​​multiple times to observe data changes in real time.

Var t = 3, p = 1; function calcPhotos(total_photos, prev_total_photos) ( var total_photos_diff = total_photos - prev_total_photos; // Output the values ​​to the console console.log(total_photos_diff); // Update the values ​​t = t*1.3; p = p*1.1; ) setInterval(function() ( calcPhotos(t,p); ),100);

Highlighting messages

In the example above, the loop will print many variable values ​​to the console. However, it is often useful to visually separate different data to effectively highlight areas in the code that require more attention. To solve such problems, the Console API has several methods.

console.info(): Displays the "information" icon and colors the information being presented. This method convenient to use to warn about various events.

console.warn(): Displays a warning icon and colors the information being presented. Convenient to use for information about parameters exceeding limits.

console.error(): Displays an "error" icon and colors the information being presented. Useful for reporting errors and critical conditions.

Note: tool Chrome developer does not have the means to present information differently in the console.

Usage various methods to output information to the console allows you to present data in a visual form. The presentation of information can be improved by blocking. Method used console.group() :

// First group console.group("Photo calculation"); console.info("Total difference is now " + total_photos_diff); console.log(total_photos_diff); console.groupEnd(); // Second group console.group("Incrementing variable"); console.log("Total photos is now: " + t); console.log("Prev total photos is now: " + p); console.groupEnd();

This example will group information in the console. Visual appearance will vary depending on different browsers, the picture below shows the view in Dragonfly for Opera:

The above examples represent a small list available methods from Console API. There are many other useful methods, which are described on the official Firebug page.

Interrupting script execution

Printing information to the console is a useful feature, but the code can run very quickly and still keep track of many variables.

To facilitate the debugging process, you can interrupt the execution of code at a certain point to gain access to data. Breakpoints are used for this.

Working with breakpoints

To set a breakpoint, go to the "Scripts" tab and select required script from the list. Now we look for the line where we need to interrupt the execution of the script, and click on the field with the line number to activate - a visual indicator will appear. Now we reload the page and code execution will be interrupted at the given point:

When execution is interrupted, you can place the mouse cursor over any variable and the debugger will display a tooltip with the current value.

You can then continue executing the code using special buttons, which are located at the top of the sidebar:

The sidebar allows you to track changes in code state, including the dynamics of local and global variables.

Conditional breakpoints

When debugging code, sometimes you want to stop code execution only when certain conditions are met. For example, if your script has a loop that takes 50 milliseconds to complete each iteration, it would be very inconvenient to start the execution process after stopping at each step when we only need 300 iterations. For such cases there are conditional interrupts.

In the example in the figure, code execution will not be interrupted until the value of the variable total_photos_diff will not be more than 200.

To activate a conditional interrupt, you need to right-click on the breakpoint and select "Edit Breakpoint" to display a dialog for editing the conditions for generating the interrupt.

Setting a breakpoint in code

It's not always convenient to set breakpoints using the developer tool interface in the browser. Sometimes it's easier to run the debugger from within the code special team. The example below shows how you can abort code when certain conditions are met:

If (total_photos_diff > 300) (debugger; // launch the debugger and interrupt code execution)

Other ways to interrupt code execution

In addition to using a breakpoint, the developer tool provides other options to stop code execution in different cases.

Stopping when DOM changes

If you need to debug the part of the code that controls DOM changes, then the developer tool provides you with a way to stop code execution when the DOM node changes.

In the HTML code panel when clicked right button mouse on the desired element, you can select the conditions for stopping the code (changing attributes, adding/removing descendants, deleting an element) when the DOM changes. Overload the code and when elements change, code execution will stop.

Stop when all or unhandled exceptions occur

Most developer tools allow you to stop script execution when exceptions occur. IN Chrome given The functionality can be enabled using the "Pause" icon on the bottom line of the interface.

You can choose which exceptions to stop code execution. The example below demonstrates one unhandled exception and one handled (try|catch block) exception:

Var t = 3, p = 1; function calcPhotos(total_photos, prev_total_photos) ( var total_photos_diff = total_photos - prev_total_photos; // First group console.info("Total difference is now " + total_photos_diff); // Update values ​​t = t+5; p = p+1; / / Unhandled exception if (total_photos_diff > 300) ( throw 0; ) // Handled exception if (total_photos_diff > 200) ( try ( $$("#nonexistent-element").hide(); ) catch(e) ( console. error(e); ) ) ) setInterval(function() ( calcPhotos(t,p); ),50);

Introduction to the Call Stack

If an error appears while executing your script, the methods described above will help you stop the program to analyze the error. But it is not always immediately clear where the reason lies.

When script execution is interrupted, pay attention to the right panel, which shows helpful information, which contains the Call stack.

The call stack shows the full path that led to the point where the error occurred and code execution stopped.

In the figure below, the error is intentionally generated in the function incrementValues(), which caused the code to stop executing. The developer tool shows the full call stack, which allows you to identify potentially dangerous places.

Conclusion

This lesson is a starting point for more detailed study documentation for the tool you plan to actively use.







2024 gtavrl.ru.