A detailed guide to debugging JavaScript code in Chrome Devtools. Track function calls and arguments


Hello! Continuing the topic, let's talk about debugging scripts using the browser. For example, let's take the most best browser on Earth - Chrome.

In principle, such tools are available in any browser, and if you consider that most browsers run on the same engine as Chrome, then in principle there will not be much difference. Firefox is also very good with its Firebug tool.

General view of the Sources panel

Launch the Chrome browser.

Press F12 and the Developer Tools will launch.

Go to the Source tab


There are 3 zones here:

  1. Region source files. It contains all the project files
  2. Text area. This area contains the text of the file
  3. Area of ​​information and control. We'll talk about her later

As a rule, when debugging, the source files area is not needed, so you can hide it with the button.

General control buttons


3 most commonly used control buttons:

Format This button allows you to format the code. You may need it if you want to format someone else's code. Console Very important button clicking on which opens the console. You can enter various commands and operators in JavaScript in the console. Window In the case of a large section of code, it allows you to open the code in a separate window.

Breakpoints

Let's look at the pow.js file as an example. If you click on any line of this file, a breakpoint will be set on that line.

It should look something like this:


A breakpoint is also called a breakpoint; this is more of a jargon that has been assimilated into our language and literally also means a breakpoint.

In the code where you made a breakpoint, you can look at the values ​​of variables at each step, in general, track it in every possible way.

Breakpoint information appears on the Breakpoints tab.

The Breakpoints tab is very useful when the code is very large, it allows you to:

  • Quickly go to the place in the code where the breakpoint is set by simply clicking on the text.
  • Temporarily disable a breakpoint by clicking on the checkbox.
  • Quickly remove a breakpoint by right-clicking on the text and selecting Remove.

Some additional features

  • A breakpoint can also be triggered directly from a script using the debugger command: function pow(x, n) ( ... debugger; //<-- отладчик остановится тут... }
  • Right-clicking on a line number in pow.js will allow you to create a so-called conditional breakpoint, i.e. set a condition under which the breakpoint will be triggered.

Stop and look around

Since our function runs simultaneously with the page loading, the easiest way to activate the JavaScript debugger is to reload it. To do this, press F5. And at the same time, the execution of the script will be stopped on the 6th line.


Pay attention to the information tabs:

  • Watch Expressions– here you can see the current value of the variables that you are monitoring in the script.
  • Call Stack– shows the call stack - these are all the calls that led to this line of code.
  • Scope Variables– shows variables. Moreover, it shows both global and local variables.

Execution Management

Now let's run the script and track its operation. Pay attention to the panel at the top there are 6 buttons, the operation of which we will consider.

– continue execution, or you can press the F8 key. This button continues execution of the script. This way we can step through our script as if it were running in a browser. – take a step without going into functions, or F10 key.

Execute one step of the script without going inside the function.

– take a step inside the function, key F11. Executes one step of the script and at the same time goes inside the function. – execute until exiting the current function, key Shift+F11.

executes the entire code contained in the function.

– disable/enable all breakpoints. This button simply disables and, when pressed again, enables all breakpoints. – enable/disable automatic stop when an error occurs. This button is very useful when debugging and allows you to enable or disable automatic stopping when an error occurs.

The debugging process itself consists of going through the program step by step and observing the values ​​of the variables.

Browser Console

When debugging script code, it can be useful to go to the Console tab and see if there are any errors there. You can also output information to the console using console.log().

For example:

// the result will be visible in the console for (var i = 0; i< 6; i++) { console.log("значение", i); }

The console is available in any browser

Console errors

JavaScript script errors can be viewed in the console.

In the console you can see:

The red line is the actual error message.

Total

The debugger allows you to:

  • Stop at the marked point (breakpoint) or at the debugger command.
  • Execute code - debug the program one line at a time or to a certain point.
  • Monitor variables, execute commands in the console, etc.

In the developer tools there are other tabs like Elements allows you to view the HTML code of the page, Timeline shows how many files the browser downloads and how much time it takes. But these tabs are not very interesting to us yet.

Published: March 26, 2013

Chrome Developer Tools is, in my opinion, the most convenient web development tool. It contains all the necessary functionality for creating and debugging full-fledged web applications. But, like any other tool, you need to learn how to work with it. Let's start with the basics.

The console plays the role of an interactive JavaScript interpreter. It also displays errors that occur while the web application is running. In addition to a separate tab, the console is available on all other tabs by pressing Esc or the console icon in the lower left corner of the screen.

The console gives the developer access to a number of convenient and useful functions. Let's consider the main ones:

console.log() , console.error() , console.warn() and console.debug()

Basic console output functions allow you to output arbitrary messages to the console. They differ in the classification of output messages: error() marks messages as errors, warn() marks messages as warnings, debug() marks messages as debugging.

These functions accept an unlimited number of parameters, which allows you to display several variables in a row and even glue them together into entire sentences:

Console.log("Log time:", 1121102802);

There is also formatting support:

Console.log("Logging time: %d", 1121102802);

Supported format indicators:

// %s — string console.log("%s", "Hello"); // %d, %i — integer console.log("%d", 1337 / 42); // %f is a floating point number console.log("%f", 1337 / 42); // %o is a DOM element console.log("%o", document.body); // either console.dirxml(document.body); // %O is a JavaScript element console.log("%O", document.body); // either console.dir(document.body); // %c — output with setting CSS styles console.log("%chello %cworld", "color: red", "color: blue");

console.trace()

Prints the call stack from the point in code where the method was called. The call stack includes file names and line numbers plus a count of calls to the trace() method from the same point.

console.assert()

The assert function checks the expression passed as the first parameter, and if the expression is false, writes an error to the console along with the call stack:

Var two = 3; var three = 2; console.assert(two< three, "два меньше трех");

console.group() , console.groupCollapsed() and console.groupEnd()

Functions for grouping output. The group() function opens a message group, takes the group name as a parameter (formatting is supported as in console.log()), and the groupEnd() function closes the last opened group. The groupCollapsed() function is similar to the group() function, but the message group that is created is collapsed by default.

console.time() and console.timeEnd()

Functions for calculating code execution time. The time() function starts a timer, and the timeEnd() function stops the timer and prints its value. Both functions accept the timer name as a required parameter.

Message filter

In the lower right corner of the console tab there is a message filter by type. All corresponds to all messages, Errors - errors and the output of the console.error() function, Warnings - warnings and the output of the console.warn() function, Logs - the output of the console.log() function, Debug - the output of the console.debug() , console functions .timeEnd() and other information.

Interaction with other tabs

debugger;

When the browser reaches the debugger line; in any code, it automatically stops script execution at this point and goes to the Scripts tab (Sources).

$() , $$() and $x()

Functions that make it easier to select elements only work in the console. The $() function returns the first element matching the selected selector. The second parameter can be used to pass the search context:

$("head") // returns the head element $("head", document.body) // returns null because body contains no head elements

The $$() function is similar to $() , but returns all elements found:

$$("script") // returns all script elements $$("script", document.body) // returns all script elements contained in body

The $x() function returns all elements matching the XPath expression. The second parameter can be used to pass the context:

$x("//script") // returns all script elements $x("script", document.body); // returns all script elements contained directly in body

Many JavaScript frameworks define their own $() function, and therefore the meaning of the functions in the console also changes.

$0 — $4

The console stores in memory references to the last five elements selected in the Elements tab. To access them, the variables $0, $1, $2, $3 and $4 are used. $0 stores a link to the currently selected element, $1 to the previous one, and so on.

$_

The $_ variable stores the result of running the last command in the console. This allows the result of one command to be used in another command. Try these commands one by one:

1337 / 42; console.log("%d", $_);

inspect()

The inspect() function opens the passed object or element in its corresponding tab:

Inspect($("head script")) // will open the Elements tab and highlight the first script tag found inside head

Forget about debugging with console.log forever! Learn how to use breakpoints to debug code in Chrome Developer Tools

Translation of the articleBrandon Morelli : Learn How To Debug JavaScript with Chrome DevTools . Published with permission of the author.

Finding and fixing errors can be difficult. You may be tempted to use console.log() uncontrollably to get your code to work correctly. It's finished!

This article is about the correct way to debug! You'll learn how to use Chrome Developer Tools to set breakpoints and examine code. This approach is often the most effective way to find and fix errors in your code.

This tutorial shows how to debug one specific issue, but a similar workflow is useful for debugging all types of JavaScript errors.

Step 1: Reproducing the error

Reproducing the error—the first step to debugging—means discovering the series of actions that lead to its appearance. You may have to reproduce the bug many times, so it is advisable to eliminate any unnecessary steps.

To reproduce the error that we are going to fix during this tutorial, follow the instructions below:

  • Here is the web page we will be working with for this article. Open it in a new tab: DEMO.
  • In demo for Number 1 enter 5.
  • Enter 1 for Number 2.
  • Click Add Number 1 and Number 2.
  • Look at the label below the inputs and button. She says that 5 + 1 = 51.

Oops. This is an incorrect result. The result should be 6. This is the error we are going to fix.

Step 2: Pause code execution using a breakpoint

DevTools allows you to pause your code mid-execution and retrieve the values everyone variables at this point in time. The tool for pausing code is called a breakpoint. Try it now:

  • Return to the demo and open DevTools by pressing Command+Option+I (Mac) or Control+Shift+I (Windows, Linux).
  • Go to the tab Sources.
  • Click Event Listener Breakpoints to expand the menu. DevTools reveals a list of event categories such as Animation And Clipboard.
  • Expand event category Mouse.
  • Select click.
  • Returning to the demo, click again Add Number 1 and Number 2. DevTools will pause and highlight the line of code in the panel Sources:
function onClick() (

When you hit click you set a breakpoint based on all click events. When the click occurs any node and this node has a click event handler, DevTools automatically stops execution on the first line of click handler code for this node.

Step 3: Explore the Code

One common cause of errors is that the script is executed in the wrong order. By examining the code, you can execute the code one line at a time and find out exactly where it is executed in an unexpected order. Try it now:

  • On the panel Sources in DevTools click Step into next function call.
Step into next function call button

This button allows you to execute the onClick() function one line at a time. DevTools will stop execution and highlight the following line of code:

If (inputsAreEmpty()) (

  • Now click the button Step over next function call.
Step over next function call button

This tells DevTools to execute the inputAreEmpty() function without going into it. Please note that DevTools skips several lines of code. This occurs because inputAreEmpty() evaluates to false , so the if statement block of code is not executed.

This is the basic idea behind code exploration. If you look at the get-started.js code, you'll see that the error is probably somewhere in the updateLabel() function. Instead of examining every line of code, you can use a different type of breakpoint to pause the code closer to where the error occurs.

Step 4: Set another breakpoint

The most common breakpoints set on lines of code are when you have a specific line of code that you want to pause. Try it now:

  • Look at the last line of code in updateLabel() :
label.textContent = addend1 + "+" + addend2 + "=" + sum;

To the left of the code you can see the number of that particular line: 32 . Click on it. DevTools will place a blue icon over the number. This means there is a breakpoint on that line. DevTools will now always pause before it.

  • Click the button Resume script execution:
Resume script execution button

The script will run until it hits a breakpoint.

  • Look at the lines of code already executed in updateLabel() . DevTools outputs the values ​​of addend1, addend2 and sum.

The sum value looks suspicious. It looks like it is being treated as a string when it should be a number. This may be the reason for our error.

Step 5: Checking the Variable Values

Another common cause of errors is when a variable or function generates values ​​other than expected. To see how values ​​change over time, many developers use console.log() , but console.log() can be tedious and ineffective for two reasons. First, you may need to manually edit code with a lot of console.log() calls. Second, you may not know exactly which variable is associated with the error, so you may need to log many variables.

Watch Expressions is a DevTools alternative to console.log() . Use Watch Expressions to track the value of variables over time. As the name suggests, Watch Expressions is not limited to just variables. You can store any valid JavaScript expression in Watch Expression. Try it now:

  • On the panel Sources DevTools click Watch. The section will open.
  • Click Add Expression.
Add Expression button
  • Enter typeof sum .
  • Press Enter. DevTools will show: typeof sum: "string" . The value to the right of the colon is the result of your Watch Expression.

As expected, sum is treated as a string when it should be a number. This is the reason for our error in the demo.

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. Increasing popularity and ease of use have led to the emergence of full-fledged applications, such as Gmail, that contain thousands of lines of JavaScript, placing increased demands on the development team in terms of tool proficiency.

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

This lesson provides a brief overview of the capabilities of modern developer tools that help make debugging JavaScript code an easier 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 console is a programmer's best friend. The multi-purpose panel is 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):

  • in the 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 is 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: The Chrome Developer Tool does not have the ability to display information differently in the console.

Using various methods to output information to the console allows you to present the 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. The visual presentation will vary in different browsers, the figure below shows the view in Dragonfly for Opera:

The above examples represent a small list of available methods from the 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, you need to go to the "Scripts" tab and select the desired 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 the special buttons 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 is easier to launch the debugger from the code using a special command. 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.