Click here to Skip to main content
15,867,704 members
Articles / Web Development / HTML

Debugging the Web: Learn How to Debug JavaScript with the Chrome Dev Tools

Rate me:
Please Sign up or sign in to vote.
4.14/5 (4 votes)
28 Feb 2019CPOL8 min read 8.7K   3   1
In this article, we learn: What Chrome DevTools is and some of the tools that it provides, how to set breakpoints and navigate through JavaScript, how to use the Console with the debugger to help navigate and understand why your code is acting the way it is.

Starting off as a new web developer, you’ll need to learn a lot of tools, and while we can’t cover every tool, we can learn about what is perhaps the most important tool any web developer should have in their arsenal: The Chrome DevTools.

If you’re unfamiliar with it, the Chrome DevTools is a set of web development tools built into the Chrome browser. Every major browser has a similar development tool, but I’ll be exclusively talking about the Chrome DevTools. You can still follow along on another browser, but it won’t be a perfect match.

You might have already accidentally opened the DevTools when browsing on the web, but for the sake of thoroughness, you can launch the DevTools by pressing F12 or right-clicking on a webpage and pressing the Inspect menu button.

Image 1

The first thing you’ll see when you open the Chrome DevTools is the HTML and CSS used on the webpage. That’s as far most people will get, but do you know that the Chrome Dev tools can show you even more?

With the Chrome DevTools, you can:

  • Examine the HTML and CSS on the Elements tab
  • Run and execute JavaScript in the Console tab
  • Examine the files used in the web app in the Sources tab
  • See the network requests made from your website in the Network tab
  • Much more!

For debugging your codebase, nothing is more efficient than stepping through your code to see what happens. I’m going to show you how you can use the Chrome DevTools to do that for JavaScript, like you would with an IDE for any other programming language.

To get us started on learning how to debug with the Chrome DevTool, we’re going to create a simple To-do list app.

Step 1: Creating a Simple To-do List App

Before we debug we need something to debug, so we’ll create a simple To-do list app. When making a task, we will take three pieces of information:

  1. The title of the task (required)
  2. The due date of the task (optional)
  3. A description of the task (optional)

We’re not going to implement any extra features except for adding a new task into our list.

Here’s what our HTML page looks like. I called it index.html:

HTML
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>To do List</title>
  </head>
  <body>
    <div>
      <div>
        Title: <br>
        <input type="text" id="title" />
      </div>
      <div>
        Date: <br>
        <input type="date" id="date" />
      </div>
      <div>
        Description: <br>
        <textarea id="description"></textarea>
      </div>
      <button id="addButton" onclick="addTodoElement()">Submit</button>
    </div>
    <span><h1>TODO List:</h1></span>
    <div id="content"></div>
    
    <script type="text/javascript" src="index.js"></script>
  </body>
</html>

Here’s what the HTML looks like on the browser:

Image 2

There’s nothing complicated in this page. The five key HTML elements we have are:

  1. A textbox for our users to write the title of their task
  2. Date input for our users to put the due date of their task
  3. A text area for the user to put in a description of their task
  4. A submit button to add the user’s task. We added an onclick event handler that will call our JavaScript function addTodoElement() which you can see below
  5. A content container div that stores all the tasks that we add in our app

I also created another file, called index.js, that holds the JavaScript that executes when our user clicks on the submit button. Here’s what it looks like:

JavaScript
function addTodoElement(){
  // Get the user's inputted values
  var todoContainer = document.getElementById("content");
  var title = document.getElementById("title").value;
  var date = document.getElementById("date");
  var desc = document.getElementById("description").value;

  // If the user didn't give a title, stop the click event
  // as it's pointless to have a task without a title
  if(title == "") {
    alert("Title is required!");
    return;
  }

  // Create a new div to contain our task information
  // with basic styles
  var todoItem = document.createElement("div");
  todoItem.style.border = "solid 1px black";
  todoItem.style.marginBottom = "5px";

  // Create the HTML for the title
  var titleParagraph = document.createElement("p");
  titleParagraph.textContent = title;
  todoItem.append(titleParagraph);

  // Create the HTML for the date
  var dateParagraph = document.createElement("p");
  dateParagraph.textContent = date;
  todoItem.append(dateParagraph);
  
  // Create the HTML for the description
  var descParagraph = document.createElement("p");
  descParagraph.textContent = desc;
  todoItem.append(descParagraph);

  // Add our new task to our container
  todoContainer.append(todoItem);
}

As you can see, index.js holds one function. This function reads the user’s inputs, creates a task, and adds it to our webpage.

Let’s try to use our app to make a task. Here’s what you get:

Image 3

Uh oh, our date doesn’t look correct. We have a bug!

Step 2: Debug JavaScript in the Sources Tab Using the Chrome DevTools

To figure out what’s causing the bug, we need to investigate the code causing the bug and figure out where the problem is appearing. In this example, we only have one function, so it’s obvious where our offending code will be.

To search through our code while it’s running, we need to set breakpoints in our code. With the breakpoints in place, any time the site uses that line of code, the Chrome DevTools will pause execution of the code and allow us to start debugging. To start adding breakpoints ...

  1. Open the Chrome DevTools by hitting F12
  2. Change to the Sources tab next to the Console

Image 4

The Sources tab shows us the files being used by our app. In this instance, the files are index.html and index.js.

The code that we want to debug is in index.js. Click on it and you’ll see that it is indeed the same file we created above.

Step 3: Creating Breakpoints and Navigating Our JavaScript Code

With our code open, we now need to set our breakpoint. This is done exactly like how you would do it with any other IDE.

  1. Click on the line number on the left side to create a breakpoint. For our demo, click on line 3.

    Image 5

Now, all we need to do is get that code to run.

  1. Clear your inputs for this next example.
  2. Click on the Submit button in our webpage and to hit our breakpoint, causing us to pause on line 3.

Image 6

To control the flow of the code, there are four buttons to know. If you’re familiar with debugging code, there shouldn’t be any surprise to you:

Image 7

From left-to-right, we have:

  • Resume (F8)– Resume will continue the execution of your code, skipping everything until either the next breakpoint or until the code finish executing.
  • Step Over (F10) – Step Over will execute the line you’re on and move you to the next line. If the line you’re on is executing a function, you’ll step over it and move to the next line.
  • Step Into (F11) – Step Into is like Step Over, but Step Into will make you go in the function and allow you to also debug the newly executed function.
  • Step Out (Shift + F11) – Step Out is used alongside with Step Into. It allows you to jump out of the current function that is being executed and go back to the code that executed the function.

Start walking through our code.

  1. Hit Step Over four times so that you are at line 10.

At this point, we’ll notice that our title variable is empty, which means we’re going to enter the if statement and stop the execution of our code without getting to the bug we’re looking for.

Image 8

Step 4: Using the Console to Help Debug our Code

Let’s pretend we’ve spent a lot of time debugging our code and don’t want to stop here. Luckily for us, there are some tricks that we can do to get around this.

Let’s pull up our Console.

  1. Right-click anywhere in your script to open the menu
  2. Click Evaluation in console

This will open the Console in our Sources tab.

Image 9

If you’re unfamiliar with the DevTools console, the console allows us to write and execute JavaScript right in our browser.

What makes this useful in this situation is that when you’re debugging, you can access the variables that we have instantiated. You can also modify variables, but for now we’ll just look at what’s currently stored:

Image 10

Typing our values in the console, we can see our bug. Why is date returning us an input instead of a value?

With that hint in mind, we now know we should look at where the value is being assigned. If we look there, we can see that we’ve made a mistake and used our input element as our date instead of getting the value from the input.

Image 11

If we were to look at the Scope window on the right of our source tab, we can see the same information that we printed.

Image 12

The console can also run functions alongside with printing variables. We can confirm our mistake typing the correct JavaScript code in our console:

Image 13

Bingo! Our value is empty because we didn’t set anything in there, but at least it’s not that hideous [object HTMLInputElement]!

Before we stop debugging, remember what we talked earlier, about how we can pass the if statement? We can do that by modifying our title variable from the console.

  1. In the console, type title = "fake title"

Image 14

If we go back to our code and highlight title, we’ll see that our title variable has the new value we set it!

  1. If you click Step Over, instead of going into the if statement, we’ll skip to line 17.

Image 15

This is a useful trick to try different inputs in the debugger without having to stop the debugger and manually try new values in the app.

If you step through the rest of the code, you’ll see that:

  1. Our "fake title" value is used for the task item.
  2. We would see that we assign our date input HTML as the textContent instead of its value.

In the end, we’ll get something like this:

Image 16

Step 5: Applying the Fix to our Script

Now that we’ve found it, let’s apply the fix to line 4. Before, we were setting date to be the input element DOM, but instead its value, we accidentally set our variable to be the DOM element. Let’s fix it:

Image 17

If we were to run our app now, we should have this:

Image 18

With that, our web app works like we expect it to! Great work!

Conclusion

Going through this small example, I hope I have shown you the power of the Chrome DevTools and how it can simplify debugging.

To summarize, in this article you should have learned:

  1. What the Chrome DevTools is and some of the tools that it provides
  2. How to set breakpoints and navigate through JavaScript
  3. How to use the Console with the debugger to help navigate and understand why your code is acting the way it is.

With this knowledge, you should be ready to start debugging your own application and help make the web a better, bug-free place!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Joshua is a passionate software developer working in the Seattle area. He also has experience with developing web and mobile applications, having spent years working with them.

Joshua now finds his spare coding time spent deep in the trenches of VR, working with the newest hardware and technologies. He posts about what he learns on his personal site, where he talks mostly about Unity Development, though he also talks about other programming topic that he finds interesting.

When not working with technology, Joshua also enjoys learning about real estate investment, doing physical activities like running, tennis, and kendo, and having a blast with his buddies playing video games.

Comments and Discussions

 
PraiseGood Article Pin
Member 115857181-Mar-19 14:12
Member 115857181-Mar-19 14:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.