What I’m expecting this code to do is append some numbers to the DOM. Specifically, I’m expecting to see 3, 4, 5, 6 and 7 on the screen, but what I’m getting back is 3, 22, 5, 6, 7. Because this is a really simplified example you might already be able to see the problem, but just imagine that the data you are working with is coming from an API or maybe you’re grabbing it from user input. Ok, so let’s try to figure out where we’re going wrong!
After you set the breakpoint, refresh the page and you’ll notice your code stops executing at the breakpoint.
You can see the dev tools have already provided a lot of extra information for us. Highlighted in our code is some valuable information about the current state of our variables, and if you hover over some of the elements dev tools also provides additional information.
Now, we’re going to start looping through our code, but we’ll be able to control each line and and analyze our output. To do this, we’re going to use the buttons circled in the above photo. Specifically for this intro, we’ll use the button called “step over”, which is the circle with the curved arrow over it. Press the button once and the highlighted line of code will be executed, pushing the highlighter down to the next line. Hit the same button again and the process repeats, allowing you to run one line of code at a time. Keep an eye on the information provided in the window, it will continually update as the variables change. Once we get through each line of code in the loop, the dev tools push us back up to the beginning of the loop because the conditions of the for loop have not been satisfied. After we run through the loop a couple of times, we can see that relevant number in the array has turned to “22”. Upon further investigation, we see that the last line of code to be run was an operation to add 2 to the existing value. Our error is happening because the original value is of type string, so when we tried to add 2 to “2” the program instead concatenated the value into the string “22”.
You might notice that if you refresh your page, the breakpoint continues to be in effect. This can be solved simply by clicking on the blue arrow that denotes the breakpoint and refreshing the page again.
There you have it, we debugged our code using the basics of Chrome Dev Tools! Stay tuned for the next post on shortcuts to speed up the workflow and some insight on the plethora of other features the “Sources” panel contains.