Search within TutorialsPark

Javascript Error : Debugging

Learn to output debugging information using various techniques.

Javascript Errors : Debugging your Code

Earlier JavaScript debuggers were not easily available, hence developers used various innovative techniques to debug code, most common among them was using the alert window.

But use of alert window method was tedious and not full proof, hence they got replaced by various other techniques.

Javascript Errors : Logging Error Messages to Console

All major browsers have a builtin JavaScript console which enables the user to view Errors in the JavaScript codes, you can even write directly onto the console from the code itself.

For this purpose you need to use the JavaScript console object to write errors in the console. The following are the methods available to do the same:

error(msg) : Used to log an error message to the Browser Console

info(msg) : Used to log an informational message to the Browser Console

log(msg) : Used to log a general message to the Browser Console

warn(msg) : Used to log a warning message to the Browser Console

You can see the JavaScript console by going to "Developer Tools" within you browser menu, or you can use the short cuts as provided below.

Google Chrome : CTRL + SHIFT + J to open console tab.

Apple Safari : CTRL + ALT + I to open Web Inspector.

Mozilla Firefox : CTRL + SHIFT + K to open Web Console tab.

Opera: CTRL + SHIFT + I to open Dragon Fly tab.

Internet Explorer : F12 to open Developer Tools, within which visit the "console" Tab.

Javascript Errors Demo: Logging Error Messages to Console

In the below demo, as soon as the function multiply() is called multiple messages are sent to JavaScript console for debugging.

The function log() is used to determine the JavaScript console and then apply the appropriate method.

Example: Javascript Errors : Logging Error Messages to Console.

Give it a TRY! » Note: Rather than using alert windows, logging to console is more efficient.

Javascript Debugging : How to Log Messages to the Page?

Another innovative way to display debugging messages to the user is to specify an area on the webpage where the message can be displayed, and then write all messages there.

Example: JavaScript Debugging : Logging Error Messages to Page

Give it a TRY! » Note: All CSS styles are optional.

Javascript Debugging: Throwing Errors

Another innovative way to debug code is by throwing errors.These errors messages must specify the exact nature of error and the causes

In order to throw a custom error use the function throwIt(), it checks for a condition to be true, and if the condition is false an error is thrown.

Example: JavaScript Debugging : Throwing Errors

Give it a TRY! » Note: The function throwIt() is used instead of multiple if statements.