What is the purpose of the JavaScript debugger keyword?

3

I was browsing the documentation for ECMAScript and I came across the < in> reserved keywords

Follows:

  

The following tokens are ECMAScript keywords and may not be used as   Identifiers in ECMAScript programs.

     

Keyword :: one of

break do instanceof typeof case else new var

catch finally return void continue for switch while

debugger function this with default if throw delete in try

All these keywords I know, and I use, one more often, some less, but until today I had never seen this: debugger.

I tried to apply an example of this keyword in jsfiddle but I did not understand its operation. Why does it exist? What is its use? And when to use?

    
asked by anonymous 15.02.2017 / 14:49

1 answer

6

It is equivalent to breakpoint of other languages, it pauses script execution and only works if the browser's developer tools or another debugger (as in Node.js ) is open, if it is not open it will have no effect.

For example, run the Snippet below and open Developer tools, then click on test:

function a() {}
function b() {}

function foo() {
    a();
    debugger;
    b();
}
<button onclick="foo();">Executar</button>

In Chrome / Opera will appear something like:

NotethatyouhavePausedindebugger,ifyouclicktheplaybuttonitwillcontinueuntilyoufindanotherdebugger;

  

InmostbrowserstouseplayyoucanpressF8

Howtouse

OfcourseintheexampleaboveIdonothavemuchsensetouseit,theideaofusingbreakpointandthedebuggerisyouuseitinseveralplacesandanalyzewheretheerroroccurs,forexample:

functionfoo(){a();debugger;b();debugger;c();debugger;d();debugger;codecodecode...codecodecode...codecodecode...debugger;codecodecode...debugger;}

Imaginethatyouhaveseverallibrariesorahugescriptthatyoudonotunderstandwheretheproblemis,oryoudonotknowwheretheproblemstarted,forexampleavariablemanipulatedbyvariousscriptsandfunctionsisarrivingwithnull,thenyoucanmanuallyapplymultipledebugger;combinedtoconsoleandbytestingstepbystepwhathappenstothevariable

Debuggingdoesnotexistdirectlywithvisualenvironments,therehastobeananalysisoftheoutputsandcodereturnsandthedebugger/breakpointisjustto"pause" and you can test.

For example (of course you can use the debugger anywhere in your script):

function foo() {
    x = a();

    console.log(x);
    debugger;

    b(x);

    console.log(x);
    debugger;

    c(x);

    console.log(x);
    debugger;

    d(x);

    console.log(x);
    debugger;

    code code code...
    code code code...
    x = code code code...

    console.log(x);
    debugger;
}

If you are in a browser and you have problems with some manipulation of the DOM, you put the debugger in several places and every debugger parses the DOM through the Elements     

15.02.2017 / 14:58