Debugging JavaScript code can sometimes be a little time consuming. If you are just beginning JavaScript you may find yourself using alert()
or window.alert()
a couple of times, and if you’ve been writing JavaScript for a little while, you may find yourself using console.log()
a number of times.
While these two approaches may work, they usually involve a lot of writing and deleting code, going back and forth between your browser and your editor of choice. Worst case scenario, you may ship your code with them, and consequently share information you may not want to share to users. Most linters however, like eslint , will warn you when you have console.log()
statements in your code.
Google Chrome Browser comes with tools (dev tools) that can help us in debugging JavaScript code, among other things. To quickly name a few.
inspect element
. This opens the dev tools and gives you an option to edit the css on the far right. Make sure you have google chrome installed in your computer. Let’s create a simple web page that takes the value of an input and prints the value a span on click of a button. We have two files:- index.html and app.js
<!-- index.html --> <html lang="en"> <head> <meta charset="UTF-8"> <title>Chrome Dev Tools</title> <script src="app.js"></script> </head> <body> <input type="text" id="name"> <button onclick="getData()">Get Input Data</button><br/> <span id="dataSpan"></span> </body> </html>
//app.js function getData() { // Get value of input var data = document.getElementById('name').value; // Get dataSpan DOM element var out = document.getElementById('dataSpan'); // Assign the value of data into dataSpan html out.innerHTML = data; }
The JavaScript function getData()
simply gets the value of the input named name , then gets the dom element named dataSpan , then adds the value from the input into the span.
You can open the index.html file directly in your browser, or if you have nodejs installed simply install httpster
with npm install -g httpster
then run httpster
in the root directory of this project. A simple server will be spin with your app hosted at http://localhost:3333 .
Suppose we wanted to know the value of var data
before we put it into the dataSpan , the old way would be to do a alert(data)
just after defining it, or console.log(data)
, then run the app in the browser and see the result.
function getData() { // Get value of input var data = document.getElementById('name').value; // check the value of data // alert(data); console.log(data); // Get dataSpan DOM element var out = document.getElementById('dataSpan'); // Assign the value of data into dataSpan html out.innerHTML = data; }
We’ll instead use Chrome Dev Tools to check the value using breakpoints. A breakpoint is a section/line of our code where we want the execution to stop so that we can carefully inspect the execution. With the app running in the browser, open Chrome Dev Tools by clicking on the menu at the top right corner, then More Tools > Developer Tools
This opens up Chrome Dev Tools at the bottom of the browser. Select the Sources tab/panel. On the left panel, click on app.js , the JavaScript file that we wrote.
Click on the line number in the middle section with the code var data = document.getElementById('name').value;
. It should change color, in my case it’s blue. Notice also that on the far right, the section under Breakpoints changes and includes the name of the file we have selected.
By clicking this line number, we have set a breakpoint on our code at that particular line of code. This means that when the function is run, its execution is supposed to stop where the breakpoint is. We should then be able to execute the code line by line, seeing changes made to our variables.
Enter hello world in the input field and click the button.
Notice a few things:
getData
and onclick
have been added to the Call Stack section. The CallStack holds a list of functions that have been called to run our code up to the point we have the breakpoint. Since we clicked the button, the onclick
event was raised, which in turn called the getData
function. data
, out
and this
. this
is present since we are running JavaScript in the browser, and it refers to the window object . Notice that at this point during execution, both data
and out
are undefined
since we haven’t assinged them values yet. Stepping in, stepping out and stepping over are common when debugging code using breakpoints. In the bottom right section of the Chrome Dev Tools, you will see a section that will enable you do any of the above actions. The first button with a play-pause-like sign is for resuming execution. It will continue executing our script to the end, unless we have another breakpoint. If this is the case, it will stop at the next breakpoint.
var x = getData()
, clicking step into the next function call will take the debugger into the getData
function. getData()
, clicking this will exit the function immediately and get us back to where it was called. Click on Step Over next function call . The selected line with the breakpoint is executed and the debugger selects the next. On the far right, in the Scope section, the Local variable data
changes to hello world
, which is the text we typed into the input box name . This is just a representation of our variables at this line of code. Pressing Step over next function call again, the currently selected line is executed and next line is selected. The value of out
in the Local scope changes to a dom element. You can click on the arrow beside it to expand it and view it’s properties. Clicking on Step Over next function call again will add the hello world text to the dataSpan in the browser window.
Say we wanted to perform a complex JavaScript function, which definitely needs debugging. For instance, we want users to input space separated numbers in the input field, and we will return both the sum and the product of the numbers.
//app.js function getData() { // Get space separated values from input var data = document.getElementById('name').value; // Get dataSpan DOM element var out = document.getElementById('dataSpan'); // Convert data into an array of string var nums = data.split(' '); // Convert nums into an array of numbers nums = nums.map(Number) // Instantiate sum and product var sum = 0; var product = 1; // Calculate sum and product nums.forEach(function(num) { sum += num; product *= num }); //Set text of dataspan to the result of sum and product var output = 'sum is ' + sum + ' and product is ' + product; out.innerHTML = data; }
We’ve changed the app.js
to look like above. Open the file in the browser and let’s debug it. We’ve set the breakpoint on the line with var data = document.getElementById('name').value;
by clicking on the line number. Enter 23 24 e in the input. I’ve included the e to induce an error since we can’t add/mutlipy numbers and alphabets.
Click on the Step Over next function call button
var data
is assigned 23 24 e
. And updated in the Scope section under Local, and beside the line of code in the middle section of the Chrome Dev Tools. nums
is now an array of strings. sum
and product
. A long version of the function would be
nums = nums.map(function(value) { return Number(value); });
You can read more about the array map function .
nums
as an array of numbers. However, the last value is a NaN
(NotANumber), since we tried to convert the letter ‘e’ into Number. We immediately can tell the our code has a bug. Let’s continue to see what happens. NaN
. This tells us immediately that we need to go fix our code. Sometimes, or most times, you may have a lot of code, probably concatenated into one file. For instace, 1000 lines of code. Setting a breakpoint in the chrome dev tools by clicking on the Line of code may seem unrealistic.
Chrome Dev Tools has a nifty feature for adding breakpoints based on common events that occur in the browser. On the far right of the dev tools, just after the breakpoints section, you will see categories of breakpoints. As you can see above, we’ve set breakpoints at every mouse click
event within our script. Clicking on the Get Input Data without setting a manual breakpoint like we did earlier, should stop execution at where the onclick
function is, which in this case is in our html file. Clicking Step Over next function call continuously will take you through the code involved in handling the onclick
method.
From the Event Listener Breakpoints section, you see that you can add breakpoints for a lot of events, including touch , keyboard and XHR .
Doing the little debugging we have done here using either console.log()
or alert()
would have taken us back and forth between the browser and our code. We would probably have had a couple of console.log
and alert
statements to get to where we are.
When your codebase becomes bigger and bigger, Chrome Dev Tools breakpoints could really be helpful in figuring out where the bugs are, and just general debugging.
If you like a dark theme for your Chrome Dev Tools, simply click on the menu icon just before the close button within the chrome dev tools, then go to Settings > General , under Appearance go to Theme and select Dark .
转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Debugging JavaScript with Chrome DevTools Breakpoints