Often, during development, the code does not work as intended or does not work at all. I sit for hours, wondering: what and where is wrong?

And sometimes I just go to prof. resources, such as Stack Overflow and publish the question "Where is the error here?" or "Why doesn't it work?"

As a result, the problem is often a petty, stupid typo, syntax error, and so on. So you will not become a professional if you run through resources for every nonsense. And I want them to be.

Question : what are the ways to find errors in Javascript code? What tools, methods, plugins, paths, etc.?

  • But about the tests will be an option? - Mikhail Vaysman
  • @MikhailVaysman about tests - as for me, it’s more like maintaining the code in working condition, rather than catching at the initial stage. but according to JS from me there will be no more answers yet. if you want to add - you are welcome ... later there will be a list for finding errors in different languages ​​... loading ... - Alexey Shimansky
  • TDD just for catching at the initial stage. I will try to write. - Mikhail Vaysman
  • @MikhailVaysman is the only thing I want to draw attention to - now it is tightly tied to the language, and not common tools and practices. - Alexey Shimansky
  • got it I'll keep it on mind. - Mikhail Vaysman

4 answers 4

Yesterday everything worked, but today it does not work / The code does not work as intended

or

Debugging


What is the debugging process? What it is?

The debugging process consists in the fact that we stop the execution of the script in any place, we look at what is in the variables, in the functions, analyze and move to other places; look for those places where the behavior deviates from the correct.

The example with Сhrome will be considered, but the code can be debugged in any other browser and even in the IDE .

Open the developer tools. Usually they open by pressing the F12 button or in the ИнструментыИнструменты Разработчика menu. Select the Sources tab

enter image description here

Numbers denoted by:

  1. The hierarchy of files connected to the page (js, css and others). Here you can select any script for debugging.
  2. The code itself.
  3. Additional features to control.

In section 2, on the left, on any line, you can click the LMB , thereby setting a breakpoint (breakpoint - breakpoint). This is where the debugger will automatically stop running javascript as soon as it comes to it. The number of breakpoints is unlimited. You can put everywhere and a lot. The image above is marked in green.

In the stopped code, you can see the current values ​​of variables, execute various commands, etc.

And in the Breakpoints tab you can:

  • Temporarily disable breakpoint (s)
  • Remove breakpoint (s) if not needed
  • Quickly go to the place of the code, where there is a breakpoint by clicking on the text.

We start debugging

In this case, because the function is executed immediately when the page is loaded, then to activate the debugger it is enough to reload it. Otherwise, the activation requires the execution of an action in which the execution of the desired part of the code will occur (click on the button, fill the input with data, move the mouse and other actions)

In this case, after reloading the page, the execution will "freeze" on line 4:

enter image description here

  • Tab Watch - shows the current values ​​of any variables and expressions. At any time here you can click on + , enter the name of any variable and see its value in real time. For example, data or nums[0] , or nums[i] and item.test.data.name[5].info[key[1]] , etc.

  • Call Stack tab - call stack, all nested calls that led to the current code point. At the moment the debugger is in the getSum function, line 4.

  • Scope Variables tab - variables. At the current moment, the lines below number 4 have not yet been completed, so sum and output are equal to undefined .

Local shows variable functions: declared via var and parameters. In Global - global variables and functions.

Process

For the process itself controls are used (see the image above, highlighted with a green rectangle)

enter image description here ( F8 ) - continue execution. Resumes script execution from now. If there are no other breakpoints, the debugging ends and the script continues. Otherwise, the work is interrupted at the next breakpoint.

enter image description here ( F10 ) - takes one step without going inside the function. Those. if there is a function on the current line, and not just a variable with a value, then when you click this button, the debugger will not go inside it.

enter image description here ( F11 ) - takes a step. But unlike the previous one, if there is a nested call (for example, a function), then it goes inside it.

enter image description here ( Shift + F11 ) - executes commands until the end of the current function. Convenient if you accidentally entered a nested call and you need to quickly exit it, without completing debugging.

enter image description here - disable / enable all breakpoints

enter image description here - enable / disable automatic stop on error. If enabled, then if an error occurs in the code, the script will stop automatically and you can look in the debugger for the current values ​​of the variables, analyze and take corrective measures.

...

So, in the current code you can see the value of the input parameter:

  • data = "23 24 11 18" - a string with data separated by a space
  • nums = (4) ["23", "24", "11", "18"] is an array that is obtained from the input variable.

If we press F10 2 times, we will be on line 7; in the tabs Watch , Scope > Local and in the page with the code we will see that the variable variable has been initialized and the value is 0.

If we now press F11 , then we’ll go inside the nums.forEach closure nums.forEach

enter image description here

By pressing F10 now until the loop is over, it will be possible to observe how the values ​​of num and sum constantly change at each iteration of the loop. Thus, we can trace, step by step, the whole process of changing any variables and values ​​at any stage that interests us.

Further pressing F10 will move the code line to lines 11, 12 and, finally, 15.


Additionally

  • You can force a stop without any breakpoints if you write the debugger keyword directly in the code:

     function getSum(data) { ... debugger; // <-- отладчик остановится тут ... } 
  • If you press RMB on the line with breakpoint, this will allow you to further fine-tune the condition under which you must stop at this point. In the function above, for example, you only need to stop when sum exceeds 20.

    enter image description here

    This is convenient if the stop is needed only at a certain value, and not always (especially in the case of cycles).

More information about the capabilities of tools such as Chrome - can be read here.


2 additional

Forced debugging can be triggered by an event occurring on the page / elements. This is useful if you do not know where the processing function is located.

Chrome example:

Press F12 , go to the Sources tab and in the control functions we see the Event Listener Breakpoints tab, in which you can set any events for which the script execution will be stopped as a trigger. In the image below, an item on the event of onchange elements is onchange .

enter image description here


For Firefox :

If the function is inline, for example

 <input type="checkbox" onchange="testFunction(this);" /> 

then you can go to the Inspector, find the same element in which the event is registered and find the em icon next to it:

enter image description here

Clicking on it, according to developer.mozilla.org/ru/docs, you can see the lines:

enter image description here

where you can see the events hung on the element, script, line, the ability to click on a pause, etc.

In other cases, and also if the pause button is not found, then on the Debugger tab (debugger) you need to find an arrow, when you hover over it that says "Events". There must be an event of the selected item.

But there are no useful tabs like Chrome unfortunately for Firefox .

enter image description here

  • Cool, but for example, I teach the node, and WebStorm can not run debbag. The server does not even start. - Tvolex

Developer Console

If the code is “naughty”, it does not work - open the developer tools that are available in any browser. Usually they open by pressing the F12 button or in the ИнструментыИнструменты Разработчика menu. Select the Console tab

enter image description here

Its behavior is about the same as in the IDE - it displays in red:

  • cause of error
  • full text of the error
  • script name with error
  • line number in that script

When you click on the script name from the console with the mouse, you will immediately move to another tab with this script to the very place where you can once again see and analyze the reason:

enter image description here

Do not know English?

Open any online translator and copy the error text there replacing uppercase letters with lowercase letters:

uncaught syntax error: unexpected token)

 Непонятная синтаксическая ошибка: неожиданный токен(символ) ) 

Straight in Russian language says: syntax error. Hence, it is necessary to search in the specified direction.

    Grandfather's way

    Despite the method described below, you need to immediately note that there are wonderful tools that will quickly help you find and correct errors. One of them is the Integrated Development Environment (IDE) . More details about it can be found in the question:

    What are the ways to prevent errors, finding and eliminating them?


    About the way.

    The method itself was used even when there were no smart development environments and just wrote the code, in fact, in notebooks. Now it also works, although with smart development environments and debuggers, this is not the fastest and most efficient way . Used alert .

    Algorithm of actions:

    1. You write alert('ЛЮБАЯ_ТЕСТОВАЯ_ФРАЗА') in, for example, the middle of the script, everything below is commented! The page is reloading.
    2. If the alert does not appear, then the error is higher. Delete and write it above, everything below is commented!
    3. If the inscription appears, then the problem is lower. Delete and write it below.
    4. Repeat steps 2 and (or) 3 until we find an error.

    Example: The code below does not start.

     var test1 = 1; var test2 == 2; var result = test1 + test2; alert(result); 

    Expect to see 3, but do not see anything at all. Hence, there is a syntax error somewhere. Put the alert higher, everything below is commented!

     var test1 = 1; var test2 == 2; alert('работает или нет?'); /* var result = test1 + test2; alert(result); */ 

    Does not work. Set higher.

     var test1 = 1; alert('работает или нет?'); /* var test2 == 2; var result = test1 + test2; alert(result); */ 

    There was an inscription. So the problem was in the line below. If you look closely, you can see that they have randomly replaced the assignment sign, the equal sign.

     var test2 == 2; ^------- лишний знак 

    We fix.

    • Great, but why learn bad through alert ? :) - user207618
    • @Aid there at the very beginning says that Сейчас он тоже работает, хотя при наличии умных сред разработок и отладчиков — это не самый быстрый и эффективный способ . Unfortunately, some will persevere in ordinary editors and not look at the console .. so maybe even so ... for more reasonable ones - there is an answer about debugging) - Alexey Shimansky
    • The very mention of the way with details will be interpreted by the gifted of this world as a call to action. And to make excuses like: "Yes, this method is cool, I actually read it to SO, and even from a high-fidelity user!" - user207618
    • @Aid well, I hope, though, that people have a mind) - Aleksey Shimansky
    • one
      @ Alex78191 if you have something to add as an answer - you can write. - Alexey Shimansky

    debugging tools / resources, I recommend:

    step by step debugging and see all the time what is happening in the environment (although in principle it is an analogue of the example debugged in Chrome developed above)