JavaScript Debugging

It is very difficult to do JavaScript programming without any proper debugging tool. It is possible that you may write code that has syntax errors or logical errors, that are difficult to diagnose.

When there is an error in JavaScript code, nothing will happen. There is no any error message or you don’t have any idea where to check for the error.

It is very common to have errors during development of JavaScript code.

Debugging

Searching for possible errors in programming during development is called debugging

Debugging is a difficult task, but modern browsers come with an in-built debugger which made it easy to debug.

Built in debugging tools can be set on or off to display possible errors. Debugger can be set on or off using short cut key F12 and select console from menu.

console.log() method

If debugging support is available in browser, console.log() method is used to display information on console.

Example

<!DOCTYPE html>
<html>
<body>

console.log() method is used  to display information in browser console. Keep console open to see output.

<script>
console.log(Math.random());
</script>

</body>
</html>

Download the code Run the code

Breakpoints

In it possible to set breakpoints in JavaScript. JavaScript execution stops when a breakpoints is encounter. You can manually resume execution once code is examined.

Debugger keyword

The debugger keyword is used to stop execution of JavaScript code. It calls debugging function.

When a debugging is turned on and debugger keyword is encountered, the JavaScript execution is stopped until play button is clicked.

Example

<!DOCTYPE html>
<html>
<body>

The debugger keyword is used to stop execution of JavaScript code.

The value of variable x <span id="text"></span>
<script>
var x = 1;
var x = 1 + 2;
debugger;
document.getElementById('text').innerHTML = x;
x *= 5;
debugger;
document.getElementById('text').innerHTML = x;
</script>

</body>
</html>

Download the code Run the code

Debugging tools in different browsers

Debugging is activate in browser using pressing F12 key and select “console”.

Chrome

  • Open Browser
  • Open Menu -> More Tools -> Developer Tools
  • Select Console

Firefox

  • Open Browser
  • Open http://www.getfirebug.com
  • Install firebug extension.

Internet Explorer

  • Open Browser
  • From Menu select Tools -> Developer Tools
  • Select Console

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .