Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Writing, testing, and debugging JavaScript CHAPTER 3 103


When placing your <script> elements at the bottom of the HTML document, they should be
just before the </body> tag. This guarantees that the document object model (DOM) has
loaded and is visible to the waiting user. This also means that any elements referenced in the
JavaScript will be present on the page.

Using the Visual Studio .NET JavaScript debugger


The best developers are those who know how to run the debugger. You can learn much
about an application by pausing the execution of an application and exploring the application
variables. If you can step through the application while troubleshooting, you can understand
how the program works and find problems quickly.
Visual Studio 2012 supports debugging JavaScript better than any previous version of
Visual Studio. This section introduces you to JavaScript debugging.
The previous lesson covered nested functions, and the example was a nested function
to calculate the area of a slice of pizza. If you know the formula for this calculation, you can
calculate the area of an 18-inch pizza and divide by 8 because there will be eight pieces per
pizza. The formula is areaPerPiece = (pi x (pizzaRadius) x (pizzaRadius))/piecesPerPizza. To get
the pizzaRadius, divide the pizzaDiameter (18 inches) by 2 to get a pizzaRadius of 9 inches.
Therefore, the formula is (3.141592 * 9 * 9)/8, which equals 31.808619 square inches. The test
should look like the following:
test('Area of Pizza Slice', 1, function(){
equal(areaOfPizzaSlice(18,8), 31.808619, 'Expected 31.808619');
});

When you run the test, it will fail with the message ‘areaOfPizzaSlice’ is undefined, so you
add the areaOfPizzaSlice code as follows:
function areaOfPizzaSlice(diameter, slicesPerPizza) {
return areaOfPizza(diameter) / slicesPerPizza;
function areaOfPizza(diameter) {
var radius = diameter / 2;
return 3.141592 * radius * radius;
}
}

Next, run the test. It should pass. You now have some code that you can step through and
debug.

Setting a breakpoint
You can set a breakpoint in your JavaScript by clicking the line of code and pressing F9 or by
clicking Debug and choosing Toggle Breakpoint. If you set a breakpoint on the second line of
the areaOfPizzaSlice function, you should see a burgundy-colored dot to the left of the line,
and all or part of the line will also be burgundy-colored, depending on where your cursor
was when you set the breakpoint. Figure 3-12 shows the code with the breakpoint set. You
Free download pdf