Debugging Javascript

Running JS in the browser

  1. Create a folder called sandbox.
  2. In the sandbox folder create an html file called week1.html with the html for a basic page. (Hint: In VS Code type ! in your blank .html file...then press the tab key. You are welcome...;)
  3. Create a file called main1.js
  4. Add a script element to your week1.html file. The script element is how we let the browser know that there is some Javascript code that it needs to fetch and execute.

    There are a few special elements in HTML. They are special because the contents of those elements are not treated as HTML, but something different.

    <script> and <style> are the most common of these special tags. In the case of <style> the contents are treated as CSS (which we won't talk about much in this course). For <script> the contents are treated as Javascript.

    The <script> can be used in two ways: we can add the code we want executed inside of the element, ie:

    <script>
        let myVar = 3; 
    </script>

    ...or we can put our Javascript code inside of a separate file and link it in:

    <script src="main1.js"></script>

    This second method is considered best practice and is how we will run our Javascript in this course. The other method is often used for quick proof-of-concept hacking, but the code will usually get moved into a JS file if the code is going to be kept.

  5. Add the following code to your main1.js file:
    const PI = 3.14;
    const radius = 3;
    let area = 0;
    area = radius * radius * pi;
    radius = 4;
    area = radius * radius * pi;
            
  6. Using the Liveserver extension open the week1.html file in a browser.
  7. There is nothing on the screen! This is normal...in our HTML we didn't ask for anything to be on the screen. Open up the developer tools...check the console.
  8. Fix the errors.
  9. Add a breakpoint and step through.
  10. Add some console.log statements
  11. Refactor our area calculation to a function.
  12. Step into the function