Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Debugging

JavaScript Debugging


When writing JavaScript, it can be painful without debugging tools.


JavaScript Debugging

It is difficult to write JavaScript programs without debugging tools.

Your code may contain syntax errors or logic errors, and without debugging tools these errors are hard to find.

Usually, when an error occurs in JavaScript, no message is displayed, so you cannot find the location of the error.

Note Usually, errors occur while you are writing new JavaScript code.

JavaScript debugging tools

Finding errors in program code is called debugging.

Debugging is hard, but fortunately many browsers have built-in debugging tools.

Built-in debugging tools can be turned on or off, and serious error messages are sent to the user.

With debugging tools, we can set breakpoints (locations where code stops executing) and inspect variables while the code is running.

To enable debugging tools in a browser, usually press the F12 key and select "Console" in the debug menu.


The console.log() method

If the browser supports debugging, you can use the console.log() method to print JavaScript values in the debug window:

Example

a

=

5

;

b

=

6

;

c

=

a

b

;

console

.

log

(

c

)

;

Try it »


Set breakpoints

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

At each breakpoint, JavaScript code execution stops so that we can inspect the values of JavaScript variables.

After inspection, you can resume the code (such as the play button).


The debugger keyword

debugger The keyword is used to stop JavaScript execution and call the debugging function.

This keyword has the same effect as setting a breakpoint in a debugging tool.

If no debugger is available, the debugger statement will not work.

With debugger enabled, the code stops before the third line.

Example

var

x

=

15

5

;

debugger

;

document

.

getElementbyId

(

"

demo

"

)

.

innerHTML

=

x

;

Try it »


Debugging tools of major browsers

To enable debugging tools in a browser, usually press the F12 key and select "Console" in the debug menu.

The steps for each browser are as follows:

Chrome browser

Or you can right-click and select "Inspect", as shown below:

Firefox Browser

Safari

Internet Explorer browser.

Opera

An easier way is: right-click and select **"Inspect element"**