Wrestling with JavaScript

Dr Anton Gerdelan - Mon 25 Nov 2013. gerdela@scss.tcd.ie

Consoles

var my_var = 10;
alert ("The value of my_var is " + my_var);

Chrome

Firefox

Internet Explorer

Print to Console

var my_var = 10;
console.log ("The value of my_var is " + my_var);

function do_something_else (value) {
  if (value > 10) {
    console.error ("ERROR: The value is too big!");
  }
}

function do_something (value) {
  do_something_else (value);
}

var my_var = 11;
do_something (my_var);

Debuggers

I have some code in this page that is supposed to take my first name as a parameter, and print my full name here by adding a "Dr" to the front and "Gerdelan" to the back. It's not working though - what I get is "Anton" when it should say "Dr Anton Gerdelan".

My name is:

Breakpoints and Stepping Through Code

  1. Switch from the "console" to the tab that has your web page's files. This is called "Sources" on Chrome, and "Scripts" on most of the others. Firefox has a "Debugger" tab next to the console.
  2. Open the debug_test.js file inside the source/debugger tab
  3. You might need to click on one of the side buttons to bring up the list of files:
  1. Find the function called function start_here ()
  2. Click inside the margin on line 8 (the first line in the function
  3. This adds a marker called a breakpoint:
  1. Refresh the page. The execution of the JavaScript code will stop at the break-point
  2. Now you have a few options;
  1. Press the step into function until the code finishes
  2. You can watch the code execute one line of JavaScript at a time
  3. But how can we spot the error?

Watch List

  1. Refresh and step through the code again, but this time wait when it gets to line 4 (where it finally puts the name on the page).
  2. On the right-hand side there is a list of local variables "in scope"
  3. name is there and it just contains "Anton"
  4. But clearly we put my whole name together on line 2?
  5. Can you see the mistake?