Debugging

JavaScript is notoriously difficult to debug due to its lack of error messages. We will go over some strategies in today's lab, but more debugging strategies can be found below. We strongly recommend you read through these, for easier debugging in future assignments.

Useful Debugging Tools

There are several tools that are available to help debug JavaScript programs. For Firefox, Firebug is a popular in-browser debugging tool. For Chrome, Chrome Dev Tools are a popular choice (the Chrome Inspector tool is included with Chrome, and can be opened using Ctrl+I on Windows/Linux).

Validator tools are also useful for debugging JavaScript, and can detect common syntax errors that would otherwise be hard to find manually. You may find the W3C HTML Validator or JSLint helpful for finding errors in your HTML or JavaScript code.

Debugging JS code in Firebug

Firebug JS

Firefox's Firebug JS debugger can set breakpoints, step through code, examine values (Script tab)

The interaction pane for typing in arbitrary JS expressions (Console tab; Watch tab within Script tab)

JSLint

JSLint

JSLint: an analyzer that checks your JS code, much like a compiler, and points out common errors

When your JS code doesn't work, paste it into JSLint first to find many common problems

JavaScript "strict" mode

              
                "use strict";
                
                your code...
              
            

Writing "use strict"; at the very top of your JS file turns on syntax checking:

You should always turn on strict mode for your code in this class

Other Debugging Strategies

alert() and console.log() are useful to include in functions that you are trying to debug, and are probably going to be most helpful when debugging JavaScript in this class.

A good strategy is to start with one of these functions in the top of your .js file as a sanity check that your script was correctly linked to the HTML page. Then, add it to the first function that is called to check that the function was called correctly, and continue the process until you reach the line(s) of code that are not working as expected.

You may find it useful to pass in variable values throughout this process so that you can check whether your variables (e.g., text in an HTML tag or value in a <input> tag have the correct values.

Debugging Checklist

General Good Coding Practices

ALWAYS code with Firebug installed / Chrome console open

Incremental development: code a little, test a little

Follow good general coding principles:

Use lines and variables liberally:

Don't fear the Firebug/Chrome debugger

Exercise 1: Buggy JavaScript

The following pages have mistakes that cause their JavaScript code not to work properly. Look at the pages, find the mistakes, and correct the problems.

  1. Buggy Page #1: HTML | JavaScript
  2. Buggy Page #2: HTML | JavaScript
  3. Buggy Page #3: HTML | JavaScript
  4. Buggy Page #4: HTML | JavaScript

Exercise 1: Solution

Buggy Page #1:
HTML script tag has name of .js file misspelled. One way to discover this bug is by putting an alert at the top of the .js file, noticing that that it doesn't show, and then checking the script tag in the HTML.

Buggy Page #2:
HTML script tag is self-closing (not valid; breaks whole page in Firefox), and misspelled name of onclick attribute. Discover by using W3C HTML Validator.

Buggy Page #3:
Many syntax errors:

Buggy Page #4:
Syntax error, missing } brace. One way to discover this error is by running JSLint.

Exercise 2: What's Your Color?

Modify colorifyme.html so that when the button is clicked, it randomly decides the color of the page background. That is, it should choose a random hex value for the background between #000000 and #FFFFFF. In addition, it should replace any text in the heading tag that has the ID "mycolor" with the text, "Your Color Is <random-color>", (where random-color is the color randomly-generated for the background).

A runnable solution is located here (don't peek at the solution code!)

Once you've got that working, make your JavaScript code unobtrusive (and way cooler) by taking out the button on the page and choosing a color randomly when the page loads.

Exercise 2: Solution

              
"use strict";
window.onload = function() {
  document.getElementById("colorify").onclick = changeBackgroundColor;
};

function changeBackgroundColor() {
  var colorOptions = ["0", "1", "2", "3", "4", "5", "6", "7",
                      "8", "9", "A", "B", "C", "D", "E", "F"]; 
  var randomColor = "#";
  for (var i = 0; i < 6; i++) {
    randomColor += colorOptions[Math.floor(Math.random() * 16)];
  }
  document.body.style.backgroundColor = randomColor;
  document.getElementById("mycolor").innerText = "Your Color is " + randomColor + "!";
}
              
            

Exercise 3: Weight Conversion

Create the file conversions.js which is referenced by conversions.html. Write a function convert() in conversions.js that takes the value in the text input and converts it from either kilograms (kg) to pounds (lb) or from pounds to kilograms, depending on the value selected in the dropdown box.

The result should be displayed in the empty span with the id of #answer.

The conversion factor from pounds to kilograms is 0.45359237, and the conversion factor from kilograms to pounds is 2.20462262.

You should edit the HTML file conversions.html to add id's to the elements as necessary and you may assume valid input. A runnable version of the solution can be found here (don't peek at the solution code!)

Exercise 3: Solution

              
"use strict";
window.onload = function() {
 document.getElementById("calculate").onclick = convert;
}

function convert() {
  var input = document.getElementById("input");
  value = parseInt(input.value);
            
  var conversion = document.getElementById("convert");
  if (conversion.value == "kgtopounds") {
    value *= 2.20462262;
  } else {
    value *= 0.45359237;
  }
                                       
  var answer = document.getElementById("answer");
  answer.innerHTML = value;
}
              
            

Exercise 4: Adopt a Llama Today!

Write a JavaScript file llamas.js to be used with the given adopt-a-llama.html file so that when the Validate button is clicked, every input in the form including the textarea that has a blank value (empty string) will be highlighted with a "red" background color, as shown in the screenshots below.

If a text box already has the red background but is then changed to non-blank, and the Validate button is clicked again, then you should remove the red background color by setting the background to an empty string, "". You should not modify HTML or CSS code; write only JavaScript. Use the document.querySelectorAll function taught in lecture.

Exercise 4: Example Appearance and Behavior

Before clicking verify button:

before image

After clicking verify button:

after image

Exercise 4: Solution

              
"use strict";
window.onload = function() {
  document.getElementById("validate").onclick = checkInputs;
};

function checkInputs() {
  var inputs = document.querySelectorAll("input");
  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].value < 1) {
      inputs[i].style.backgroundColor = "red";
    } else {
      inputs[i].style.backgroundColor = "white";
    }
  }
  var textareaInput = document.querySelectorAll("textarea")[0];
  if (textareaInput.value < 1) {
    textareaInput.style.backgroundColor = "red";
  } else {
    textareaInput.style.backgroundColor = "white";
  }
}