Using the Chrome DevTools "Sources" Panel - Exercise

Contact Us or call 1-877-932-8228
Using the Chrome DevTools "Sources" Panel - 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

Next