facebook google plus twitter
Webucator's Free JavaScript Tutorial

Lesson: Debugging and Testing with Chrome

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

Chrome's Developer Tools are a valuable resource for writing and debugging JavaScript code.

Lesson Goals

  • Learn how to use Google's DevTools to debug JavaScript

Chrome DevTools

Google's Chrome browser offers a wide range of tools useful to us as front-end JavaScript developers. By right-clicking and choosing "Inspect" from the context menu (or by choosing "Developer Tools" from the "Tools" option under the Chrome menu at the upper right of the browser), we open a set of panels - positioned by default at the bottom of the browser - by which we can inspect markup code, access the JavaScript console, via network activity, set breakpoints, and find other useful resources as we create and debug our JavaScript code.

In addition to the existing "out of the box" tools, Google Chrome offers an API by which you can write your own tools to meet a specific need, or use an extension built by someone else.

The Panels

Before we take a look at the most useful of the DevTools panels, let's look at a simple page with some JavaScript we can use those tools to review and debug:

Code Sample:

DebuggingtestingChrome/Demos/debugging.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Loops</title>
<script>
	var index;
	var beatles = [];
	beatles["Guitar1"] = "John";
	beatles["Bass"] = "Paul";
	beatles["Guitar2"] = "George";
	beatles["Drums"] = "Ringo";

	

	window.onload = function() {
		for (var prop in beatles) {
			var beatle = document.createElement("li");
			var textnode = document.createTextNode(prop + " : " + beatles[prop]);
			beatle.appendChild(textnode);
			document.getElementById("beatles").appendChild(beatle);
		}

		document.getElementById("redtext").addEventListener("click", function() {
			document.getElementById("beatles").style.color = 'red';
	    	return false;
		});
		document.getElementById("blacktext").addEventListener("click", function() {
			document.getElementById("beatles").style.color = 'black';
	    	return false;
		});
		document.getElementById("italictext").addEventListener("click", function() {
			document.getElementById("beatles").style.fontStyle = 'italic';
	    	return false;
		});
		document.getElementById("normaltext").addEventListener("click", function() {
			document.getElementById("beatles").style.fontStyle = 'normal';
	    	return false;
		});
	}
</script>
</head>
<body>
<h1>JavaScript Debugging</h1>
<ol id="beatles">
</ol>
<div class="buttons">
	<ul>
		<li><a href="#" id="redtext">Set Text Red</a></li>
		<li><a href="#" id="blacktext">Set Text Black</a></li>
		<li><a href="#" id="italictext">Set Text Italic</a></li>
		<li><a href="#" id="normaltext">Set Text Plain</a></li>
	</ul>
</div>
</body>
</html>

Code Explanation

The HTML markup for our page has an empty ordered list with id beatles and a set of four links ("Set Text Red", "Set Text Black", "Set Text Italic", and "Set Text Plain"). In the head of the document we include JavaScript that:

  • Creates an array of members of the Beatles, where the index is the instrument and the value the name of each member;
  • After the DOM loads, we use a for...in loop to append each Beatle array-element to the unordered list;
  • Also after the DOM loads, we create event listeners for each of the four links, changing the text color or style when the user clicks each link.

Let's use this relatively-simple code to see how the various resources Google DevTools gives us might be of use.

The Elements Panel

The "Elements" panel is the default panel which comes up when one right-clicks on a DOM element on the page. While not strictly JavaScript, this panel is great for finding the id of an element and looking at its associated CSS styling. Information about HTML elements and their CSS styling are dynamic in this panel: changes we make via JavaScript - changing the text color, say, as we do in our sample code, and adding the Beatles order-list elements - are reflected in real time in the "Elements" panel, just as if the original HTML of the page had included what we changed via JavaScript.

For our example, we might use the "Elements" panel for a quick check of the id of the "Set Text Red" link ("what did I set that id to?") or to verify that the CSS style of the Beatles members list is set, as we intend, with color:red:

Chome DevTools Elements panel

The Console Panel

The "Console" panel gives us valuable JavaScript error information - a message from the browser that we have, sadly, written some buggy code. We might, for instance, have misspelled a JavaScript keyword, tried to access the property of a null element (in trying to get an element with an incorrect id, say), or attempted to access an element of an array that doesn't exist.

Perhaps even more usefully, we can write to this console as a simple debugging tactic. The following code would write the value of an array to the console:

var seconditem = shoppingcart[2];
console.log(seconditem);

If shoppingcart were an array - the items a user might have added to their shopping cart, for instance - then seconditem would represent the third item in the cart (the third item in the array, since JavaScript indexes arrays starting at 0). The code console.log(seconditem) writes not to the screen, but rather to the console, which we can view with the "Console" panel. A great feature here is that we can view structured data - arrays and collections - in a useful manner, along with simple data like string and arrays.

For our example, if we were to add the following code after we create and populate the Beatles array:

console.log(beatles);

Then we would be able to inspect the array:

Chome DevTools Console panel

Before reviewing more DevTools panels, let's have you try out the tools we've reviewed so far with an exercise:

Using the Chrome DevTools "Elements" and "Console" Panels

Duration: 5 to 15 minutes.
  1. Open DebuggingTestingChrome/Exercises/elements-console.html in a browser and in a code editor to review the code.
  2. This page - a modified version of the example code we looked at earlier - is designed to set the text of the "George" list item to red when the user clicks the "Set George Red" link; however the code does not work as intended.
  3. Note that we use beatle.setAttribute("id", prop); to set an id for each list item as we iterate over the array to build our ordered list.
  4. Use the Chrome DevTools "Elements" and "Console" panels to help you diagnose and fix the error.

Solution:

DebuggingtestingChrome/Solutions/elements-console.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Loops</title>
<script>
	var index;
	var beatles = [];
	beatles["Guitar1"] = "John";
	beatles["Bass"] = "Paul";
	beatles["Guitar2"] = "George";
	beatles["Drums"] = "Ringo";

	window.onload = function() {
		for (var prop in beatles) {
			var beatle = document.createElement("li");
			beatle.setAttribute("id", prop);
			var textnode = document.createTextNode(prop + " : " + beatles[prop]);
			beatle.appendChild(textnode);
			document.getElementById("beatles").appendChild(beatle);
		}

		console.log(beatles);

		document.getElementById("redgeorge").addEventListener("click", function() {
			document.getElementById("Guitar2").style.color='red';
	    	return false;
		});
	}
</script>
</head>
<body>
<h1>JavaScript Debugging</h1>
<ol id="beatles">
</ol>
<div class="buttons">
	<ul>
		<li><a href="#" id="redgeorge">Set George Red</a></li>
	</ul>
</div>
</body>
</html>

Code Explanation

The issue here is that the event handler for a user click on the "Set George Red" link references the wrong id: instead of setting the element with id Guitar2 to be red, we (wrongly) set the element with id Guitar1 to be red.

We can use the Chrome DevTools in a couple of ways to help us in our task of finding the bug in the code. First, we might have used the "Elements" console to quickly scan the ids of the list items:

Chrome Elements panel

and seeing that the "George" list item has id Guitar2. We might also have used console.log(beatles) to list the elements of our array, to compare the indices of our array against the ids we see in the "Elements" panel:

Chrome Console panel

Of course, we don't really need the DevTools here - we could have gone through the source of our code, rather than reviewing it in the browser and inspecting via DevTools - to find and fix the bug. But because DevTools makes it so easy to inspect DOM elements and view collections like arrays in the console, DevTools is often the preferred method of debugging, especially as your JavaScript code gets more complicated.

The Sources Panel

The "Sources" panel of Chrome's DevTools gives us the opportunity to add breakpoints ("pauses" in our code, where the browser will let us stop to review how things are going), to step through the execution of our code, and to watch the values of any given variable or expression. Tracking down that bug (hopefully just one!) in your thousands of lines of JavaScript code gets much easier if you can have the browser let you check the values of some variables each time you run through a loop and check out the current state of an array.

Let's look again at how we might use the tools from the "Sources" panel on our example page DebuggingTestingChrome/Demos/debugging.html. Right clicking on any part of the screen, choosing the "Inspect" from the popup menu, selecting sources, clicking on "debugging.html" from the left part of the panel gives us the following:

Chome DevTools Sources panel

We can click on the line number of any line of JavaScript code; in the example below we've clicked on line 18, in which we create a list-item node for a different Beatle on each iteration of our for loop:

Chome DevTools Sources panel

If we refresh the page, we see that Chrome pauses the execution of our JavaScript code each time we reach line 18 - pausing, in this case, in the middle of each loop. We can iterate through the loop using the "play" icon (highlighted in orange in the screenshot below) and we can see values for the various variables on the right side of the panel:

Chome DevTools Sources panel

We can use the "Watch" (in the upper right) to view the value of any variable or expression; in the example below, we clicked the "+" sign and added a watch for beatles, which lets us view the value of the array:

Chome DevTools Sources panel

You can try out the Chrome DevTools "Sources" panel in the next exercise.

Using the Chrome DevTools "Sources" Panel

Duration: 10 to 20 minutes.
  1. Open DebuggingTestingChrome/Exercises/watch.html in a browser and in a code editor to review the code.
  2. This page - a modified version of the example code we looked at earlier - is designed to add the text " - Fave!" to the "George" list element; however the code does not work as intended.
  3. Note that we use use the ternary operator in our loop, appending (or trying to append) the text " - Fave!" when we reach the list element corresponding to the "George" the array element.
  4. Use the Chrome DevTools "Source" panels to help you diagnose and fix the error.

Solution:

DebuggingtestingChrome/Solutions/watch.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Loops</title>
<script>
	var index;
	var beatles = [];
	beatles["Guitar1"] = "John";
	beatles["Bass"] = "Paul";
	beatles["Guitar2"] = "George";
	beatles["Drums"] = "Ringo";

	window.onload = function() {
		for (var prop in beatles) {
			var beatle = document.createElement("li");
			var textnode = document.createTextNode(prop + " : " + beatles[prop] + (prop == 'Guitar2' ? ' Fave!' : ''));
			beatle.appendChild(textnode);
			document.getElementById("beatles").appendChild(beatle);
		}
	}
</script>
</head>
<body>
<h1>JavaScript Debugging</h1>
<ol id="beatles">
</ol>
</body>
</html>

Code Explanation

The issue here is that the test for whether this is "George" array element is checking beatles[prop] to match the value Guitar2; however it is the index (prop) that we should be checking, not the value of the array.

We can set a breakpoint in the middle of our loop and also set a watch (on beatles[prop]) to check why our test for the "George" element of the array never returns true. Chrome's DevTools make it easy to see that we mistakenly evaluated the index of the array element rather than it's value.

Chome DevTools Sources panel

Other DevTools Panels

There are other resources - other panels - available from DevTools; while beyond the scope of this course, we encourage you to check them out. These include:

  • The "Network" panel, which is especially useful when debugging JavaScript Ajax functionality;
  • The "Timeline" panel, which can be used to diagnose the time required for various sections of a page to load or complete;
  • The "Security" panel, which is useful for checking on SSL security on a page.

For more information, visit the Google Developers DevTools documentation.

Chrome DevTools API and Extensions

Google offers an API for developers to write their own DevTools panels, to add whatever functionality might be needed for a particular developer, team, or application.

Even better than writing extensions ourselves is to make use of the work of others. Chrome lists some featured DevTools extensions on their website; a quick Google search will turn up others. You can find extensions to make easier the process of debugging and evaluating platforms and libraries like Ruby on Rails, Angular, and Ember; tools to better diagnose page speed; and tools to extract code snippets for sharing with others.

In the next exercise, we'll ask you to install and try out one of these extensions.

Accessibility Developer Tools Extension

Duration: 5 to 15 minutes.
  1. Visit the Chrome Webstore page for the Accessibility Developer Tools extension from a Chrome browser.
  2. Install the extension and restart Chrome.
  3. Visit a website of your choice and use the tools to evaluate how well the page presents code in a manner friendly for users who employ assistive technology like screen readers:
    • Right-click on any part of the page and select "Inspect".
    • Select the "Audit" panel.
    • Check the "Accessibility" option.
    • Run the audit.

The results shown in the screenshot below give a sense of how well the page uses meaningful alt tags, marks up elements, codes forms, and other aspects of how friendly the code is for users who employ assistive technology.

accessibility extension