A detailed guide to debugging JavaScript code in Chrome Devtools. Major browsers "Debug tools"

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

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 bug we are going to fix during this manual, 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 the 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 Sources tab.
  • Click Event Listener Breakpoints to expand the menu. DevTools reveals a list of event categories such as Animation and Clipboard.
  • Expand the Mouse event category.
  • Select click.
  • Back in the demo, click Add Number 1 and Number 2 again. DevTools will pause and highlight the line of code in the Sources panel:
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 handler click events, 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:

  • In the Sources panel 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 Step over next function call button.
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:

label.textContent = addend1 + "+" + addend2 + "=" + sum;

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

  • Click the Resume script execution button:
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. Firstly, you may need to manually edit the code with big amount 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 save any valid JavaScript expression in Watch Expression. Try it now:

  • In the Sources DevTools panel, 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.

We tell you how to use Chrome panel Devtools is convenient for debugging.

Finding and fixing errors can be difficult for beginners. If you are thinking about using console.log() to debug your code The best decision, then you are wrong.

In this article we will talk about great tools Google Chrome Devtools for debugging This process is much more effective way solutions to this problem.

This is just one simple example of how to use debugging, but it can be applied to any problem.

Step 1: Reproduce the bug

Reproducing bugs is always the first step towards debugging. This means finding the sequence of actions that lead to the error. The process can be long, so try to optimize it.

To follow the steps in this tutorial yourself, do the following:

  • Here is the web page we will be working with in this tutorial. Don't forget to open it in a new tab;
  • Enter the number 5 in the “Number 1” field;
  • Enter the number 1 in the “Number 2” field;
  • Click on the “Add” button;
  • Look, they tell you that 5+1=51;

Oops, that's obviously wrong. The result should be the number 6, and this error needs to be corrected.

Step 2: Pause execution using a breakpoint

DevTools allow you to stop code execution in progress and view the values ​​of all variables at that point in time. The tool for pausing code is called a breakpoint. Try:

  • Return to our test page and enable DevTools by pressing Cmd + Option + I (Mac) or Ctrl + Shift + I (Windows, Linux);
  • Go to the "Sources" tab;
  • Expand "Event Listener". DevTools will expand a list of event categories such as animation and clipboard;
  • Check the “click” box;
  • Returning to the page, add “Number 1” and “Number 2” again. DevTools will pause the demo and highlight the line of code in the Sources panel. DevTools will highlight this line of code:

    function onClick() (

    function onClick() (


    Why is this happening?

    When you select "click", you set breakpoints that depend on click events on each element that has a handler for it.

    Step 3: Perform step-by-step debugging

    One common reason why errors occur is that the script is not executed in the order you think it should. You can avoid this problem by observing the execution of the code line by line. Let's try:

    • In the "Sources" panel, click "Step into next function call button"

    This button will allow you to sequentially track the execution of the onClick function. Stop the process when DevTools highlights the following line of code:

    if (inputsAreEmpty()) (

    if (inputsAreEmpty()) (

    • Now click the “Step over next function call button”;

    DevTools now knows to execute inputAreEmpty() without debugging its contents. Please note that DevTools skips several lines of code. This is because inputAreEmpty() returns false, so the if block was not executed.

    That's the point step-by-step debugging code. If you look at the code in get-started.js, you'll see that the error is probably somewhere in the updateLabel() function. Instead of going through each line of code, you can use a different type of breakpoint to stop the process closer to where the error occurs.

    Step 4: Select a different breakpoint

    The line-of-code type is the most popular breakpoint. If you know where the error might be, use this type:

    • Look at the last line of code in updateLabel(), which looks like this:

      label.textContent = addend1 + " + " + addend2 + " = " + sum;

      label. textContent = addend1 + " + " + addend2 + " = " + sum ;

    • To the left of this code you will see a line number: 32. Click 32. Now DevTools will always pause until this line of code is executed;
    • Click the "Resume script execution button". The script will continue to run until next line code with a breakpoint;
    • Look at the lines of code in updateLabel() that have already been executed. DevTools outputs the values ​​of addend1, addend2 and sum.
    • The amount looks suspicious. It looks like it's not being evaluated as a number, but as a string. This is another one common reason errors.

      Step 5: Check Variable Values

      A common cause of errors is that a variable or function generates the wrong value. Many developers use console.log() to see how values ​​change, but console.log() is a poor choice for at least two reasons: First, it may require manual editing of code with many calls to console.log() ), secondly, you may not know which variable is associated with the error, so you will have to display several variables at once.

      One alternative to console.log in DevTools is Watch Expressions. Use Watch Expressions to track changes in variable values. As the name suggests, Watch Expressions is not limited to just variables. You can store any valid JavaScript expression in Watch Expression:

      • In the "Sources" panel, select the "Watch" tab;
      • Then click "Add Expression";
      • Type typeof sum;
      • Press enter. DevTools will show typeof sum: "string". This value is the result of Watch Expression.

      As expected, sum is treated as a string, not a number. This is the same error that we talked about above.

      Another DevTools alternative to console.log() is the console. Developers often use it to overwrite variable values ​​when debugging. In your case, the console may be handy to check ways to fix the error. Example:


      Step 6: Make Corrections

      You have identified where the error is. All that remains is to fix it by editing the code and restarting the demo. You can edit JavaScript code directly to user interface DevTools:

      • In the code editor, in the Sources panel, replace var sum = addend1 + addend2 with var sum = parseInt(addend1) + parseInt(addend2); This is line #31.
      • Press Cmd + S (Mac) or Ctrl + S (Windows, Linux) to apply the changes. The background of the code will change to red to indicate that the script has been modified in DevTools;
      • Click "Deactivate breakpoints"

      The color will change to blue. In this mode, DevTools ignores any breakpoints you have set.

      • Click "Resume script execution".

      Enter numbers in the fields and test. Now everything should work as it should!

      Firebug contains a powerful AvaScript debugger that gives you the ability to pause execution at any time and view every variable at that moment. If your code is sluggish, use a JavaScript profiler to measure performance and quickly find bottlenecks.

      Find scripts with ease

      Many web applications consist of large number files, and finding the one to debug can be a routine and boring task. Firebug's script selection menu sorts and organizes files in a clear and clear list, which will help you find any file with one click of your finger.

      Pause execution at any line

      Firebug allows you to set breakpoints, which tell the debugger to stop executing the script when it reaches specific string. While execution is suspended, you can view the values ​​of any variables and inspect objects.

      To set a breakpoint, click on any line number and a red dot will appear there, indicating that the breakpoint has been set. Click on the red dot again to remove the breakpoint.

      Pause execution only if...

      Breakpoints can cause problems if triggered too often. Sometimes we want to pause execution only when certain conditions are met. Firebug allows you to set "conditional" breakpoints. They check an expression that must be true for the breakpoint to work.

      To set a conditional breakpoint, simply click right click on any line number. A bubble will appear prompting you to enter a javascript expression. You can right click again at any time to change the expression, or left click to get rid of the breakpoint.

      One step at a time

      When the debugger has paused execution, you can continue the script one step at a time. This allows you to clearly see how executing a specific line affects variables and objects.

      You can also continue execution for more than one line. Select in context menu the desired line"Run to this Line" to continue execution to this line.

      I get interrupted when I make mistakes

      You don't always choose the debugger... Sometimes the debugger chooses you. Firebug gives you the ability to jump into the debugger automatically when an error occurs, so you can investigate the conditions under which the problem occurred.

      Unfolded stack

      When the debugger pauses, Firebug shows you the call stack, which is the collection of nested function calls that are currently running and waiting to return.

      The call stack is represented by a compact strip of buttons in the panel, each with the name of a function on the stack. You can click any button to jump to the line where the function is paused and look at the values ​​of local variables from inside the function.

      Expression Watching

      When debugging, you often want to see the value complex expressions or objects that are buried in the DOM. Firebug allows you to print an arbitrary javascript expression, the value of which will be updated at each debugger step.

      When typing expressions, remember that you can use Tab key for auto-completion of object properties.

      Variable Hints

      While execution is paused, you can move the mouse over any variables current function by viewing tooltips with values. This is a great way to keep your eyes on the code and get answers while you read.

      Profile JavaScript Performance

      Your web application is almost perfect. You have worked through all the errors, done stylish design and users love it. Just one problem - some features are slow and you're not sure why...

      With Firebug, you no longer have to wonder why your code is running slow. Using the Firebug profiler, you can separate flies from cutlets in literally seconds.

      To use the profiler, simply go to the Console tab and click the "Profile" button. Then use your application for a while or reload the page and click "Profile" again. You'll see a detailed report that shows which functions were called and how long each one took.

      Logging function calls

      Sometimes the problematic function is called so many times that you cannot go into the debugger each time. You just want to know when it is called and with what parameters.

      To track all function calls, simply right-click on the Script tab and select "Log calls to "function name"". Then go to the console and watch the calls appear in the log...

      Go straight to line 108

      Often you want to go clearly to the desired line of your script. There is nothing easier, just type the line number in the window quick search, putting # first, as shown in the left screenshot.

      It's easy to get lost writing JavaScript code without a debugger.

      JavaScript Debugging

      It's difficult to write JavaScript code without a debugger.

      Your code may contain syntax errors or logical errors that are difficult to diagnose.

      Often, when JavaScript code contains errors, nothing will happen. There are no error messages and you won't be given any instructions on where to look for errors.

      Typically, errors will occur every time you try to write something new code JavaScript.

      JavaScript Debuggers

      Finding errors in program code called debugging code.

      Debugging is not that easy. But fortunately everything modern browsers have a built-in debugger.

      Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

      With a debugger, you can also set breakpoints (places where code execution can be stopped) and examine variables while the code is running.

      Generally, otherwise follow the instructions at the bottom of this page, you will enable debugging in the browser using the F12 key, and select "Console" from the debugger menu.

      console.log() Method

      If your browser supports debugging, you can use console.log() to display JavaScript values in the debugger window:

      example



      My First Web Page


      a = 5;
      b = 6;
      c = a + b;
      console.log(c);

      Setting breakpoints

      In the debugger window, you can set breakpoints in your JavaScript code.

      On each control point, JavaScript will stop executing and allow you to explore the JavaScript values.

      After examining the value, you can resume executing the code (usually using the play button).

      Debugger Keyword

      Debugger keyword stops JavaScript execution and calls (if any) to the debugging function.

      This has the same function by setting a breakpoint in the debugger.

      If debugging is not available, the debugger statement has no effect.

      With the debugger enabled, this code will stop executing before it executes the third line.

      Major browsers "Debug tools"

      Typically, you will enable debugging in the browser with F12, and select "Console" from the debugger menu.

      Otherwise, follow these steps:

      Chrome
      • Open your browser.
      • From the menu, select tools.
      • Finally, select Console.
      Firefox Firebug
      • Open your browser.
      • Go to web page:
        http://www.getfirebug.com
      • Follow the instructions as:
        install Firebug
      Internet Explorer
      • Open your browser.
      • From the menu, select tools.
      • From tools, select developer tools.
      • Finally, select Console.
      Opera
      • Open your browser.
      • Go to web page:
        http://dev.opera.com
      • Follow the instructions as:
        add a developer console button to the toolbar.
      Safari Firebug
      • Open your browser.
      • Go to web page:
        http://extensions.apple.com
      • Follow the instructions as:
        install Firebug Lite.
      Safari Develop Menu
      • Go to Safari, Settings, Advanced in the main menu.
      • Check the "Enable Show menu in menu bar Develop" checkbox.
      • When the new "Develop" option appears in the menu:
        Select "Show Error Console".

      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, the 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