When developing a program, the only thing a developer frets is when he encounters an error! Who would not want a smooth-running piece of code with no errors in one shot!! Sounds amazing right? But practically when we develop an application errors are bound to happen; they could be syntactical or logical. This is where “Debugging” helps. The method by which the errors are identified and resolved is known as Debugging.
In JavaScript we have well-formed debugging functionality and tools to figure out cause of an issue and thus fix it. Before we dive into the details of this tutorial one is expected to be sound in JavaScript basics and if you are new to JavaScript and want to master this language then you should certainly checkout our courses here at ADMEC in JavaScript Training Institute which is one of the best courses offered in Delhi.
Now, to make JavaScript debugging easy to perform here are some features of modern debugging tools. Let’s discuss some of the features here:
Browser Developer Tools
Since JavaScript applications are viewed in a browser, every modern browser provides a functionality of debugging packaged in their developer Tools. Following are the keyboard shortcuts to access it in some of the browsers:
- Chrome: CTRL +SHIFT+ I or F12
- Internet Explorer: F12
- Mozilla Firefox: CTRL+SHIFT+J
In this tutorial we will see examples with the chrome developer tools.
Developer Tool Zone
When you open a JavaScript application in the chrome browser and open the developer’s tool, you will see this screen:
This is the Developer’s tool. It has panes which are mentioned below:
- Resources zone: Lists HTML, JavaScript, CSS and other files including images that are attached to the page.
- Source zone: Shows the source code. Under this tab you can view the code that you have created. You can select between the JS files to debug.
- Information and control zone: This gives all the controls for debugging you code.
Console
The browser’s Console is an interface that lets you log information of a JavaScript application while development and testing. In some applications developers use “alert()” method to display values while writing the code but using the console to display and test values is more optimized way of going about it.
In the above screen you can see an image of the console, it is interactive and lets you write JavaScript and gives relevant results. In this example above it displays an alert box, and displays undefined as nothing is returned.
Technically Console is an object which lets you access the browser’s debugging console. This object is sometimes also referenced as “window.console” The console has its own methods through which you can interact and test values and errors, some of the most used methods are:
- Console.log()
The console.log method in JavaScript prints the value passed to this method to the Console panel. It is better than using alert () dialogues. e.g.:
The console.log() method lets you print any type of data like a simple string , number , an array or an object. You can expand the results for arrays and objects to inspect each element within.
- Console.clear()
As the name suggests, this method clears the content of the console and displays a message “console was cleared”. This is mostly used when we have logged lot of information and want a blank message list to begin again.
Pausing Execution
Many a times a code execution does not go the way we thought it would, we may encounter an error or exception or maybe our code just crashes. In such situations a developer feels the need to “Debug” to troubleshoot any errors.
Solving Issues by Reading!
When we encounter an error the first step should be to glance your code and try to read it to find any mistakes. And most of the times if the issue is really simple just reading the code does the trick. For eg, if you are trying to print value of a variable which in the first place does not exist in your scope, the console may give you an undefined. Such mistakes can be dealt with by carefully going through the code and making changes!
For other issues to debug a code we need to pause execution to know where exactly things are going wrong. This can be performed using different methodologies, let’s see some of them:
Breakpoints
When we want the debugger to pause the JavaScript execution at a particular point for this purpose Breakpoint is used. When a JavaScript application loads in the browser, it runs until it meets a breakpoint, where execution is halted for the developer to examine current variable values or execute commands in the console.
In the debugger tool of every browser we can set breakpoints by clicking on the line number of the code from where we want to debug. For example:
In the screen above we have set a breakpoint at the line number ‘86’ and ‘89’ by clicking on them. So as soon as the page loads when execution reaches line number ‘86’ it will pause, from here on the developer can take actions which we will read about ahead.
Debugger Command
The pausing of the code can also be done with the help of debugger command.
For Example:
When you run the application the moment your code execution reaches this point it pauses for you to examine what exactly is going on in detail. This helps in saving a lot of time when we are working on a code editor and we don’t want to toggle between code editor and browser again and again to set breakpoints manually.
Tracing Execution
Up until now we saw how to pause execution for debugging, now we will see how debugging is actually done using controls provided in your browser (in our example we have Google chrome)./
Start Debugger
After setting the breakpoint, reload you page and it will automatically stop where the breakpoint is encountered. As we can see this in the screen below, as soon as the line number ‘86’ is reached upon execution our browser enters the debugging mode and displays a message “paused in debugger” .
Access Execution Controls
After entering the debugging mode the control is in the developer’s hands. For this the browser provides some controls on the right side pane of the debugger:
- Continue [F8]: Continues code execution until another breakpoint is encounteredwhich means it will resume normal execution of your code without the debugger.
- Step over [F10]: Using this command the code is surfed line by line in a way that one can notice that how the change has effected each line. The advantage here is that if suppose your code calls some other function then the debugger will not jump on its code. Rather than this it will be “stepped over” and will stay on the same function on which it was earlier.
- Step into [F11]: Step Into refers to the command where we click this at some function call and the debugger now will move its execution to the function that is being executed.
- Step Out: [Shift+F11]: Now, when you are at a function definition b clicking Step Into button, at this point clicking Step Out button will help in executing the function that is left and moves the control of the debugger back to its parent function.
- Deactivate Breakpoints
In Our example we stepped in after starting the debugger and in the screen below the control is at line ‘88’ right now. As you see in the image below the debugger highlights the line number being currently executed.
You can see the tooltip with all the details at the particular time with debugger by pausing the execution and hovering the cursor over any of the variable.
Check Values
Under the sources panel, the debugger has some tabs that let you examine values deeply. Some of the most used tabs are:
WATCH
This allows you to watch variables within your code. By using this we can avoid logging variables to the console. It lets you add expressions by clicking the + sign. Example: I have added the variable ‘elemBookAuthor’ to the watcher and also an expression ‘elemBookAuthor.type’ which shows its type. While executing it computes the value for this expression.
CALL STACK
This shows the nested function calls within a function. In the example below the call stack displays “createBooksTable()” and “calculateTotalPages()” functions, The “createBooksTable()” has been triggered by an “onclick” event and while stepping in the “calculateTotalPages()” function is called. If you select any of the itmes in the stack then the debugger will jump directly to the code corresponding to it. To examine the variables, you need to click on a stack item. After clicking the debugger jumps to the corresponding code.
SCOPE
This shows values of the current variables. With local you can see local function variables. Also the values of those particular variables can be see right above the source. Global scope basically has global variables. In our example we can see under the local variables “totalPages” and “totalRecords” are displayed.
Summary
We cannot avoid creating errors but we can solve them through debugging! Along with good programming skills it is important for a developer to have good debugging skills as well. We have seen all the aspects of how to debug a JavaScript application. What makes a developer better is hands on experience, hence here at ADMEC we believe in teaching through live demos and tutorials in the JavaScript course that we have designed which makes you industry ready!