Essential JavaScript debugging tools for the modern detective by Rebecca Hill | JSConf Budapest 2019

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so yes this is me at my day job detecting bugs yeah so I work at wetransfer as a front-end engineer and team Li and for me that means that I write mostly react HTML CSS a little bit of Ruby everyone again and I also manage a team of six and I'm responsible for the day-to-day delivery for that team and this is also me about six years ago I was helping run a workshop for young girls in New Zealand which is yeah where I'm from and yes I'm a very long way away from home but the idea was that we would get these young women into the company to sort of show them what it was actually like to be a software engineer they were about 14 years old and they were all in the same tech class at school and honestly I think we kind of blew their minds on how cool this actually is compared to what they were learning and but yeah I really want to encourage people to do as many of these kinds of programs as you can because it's incredibly rewarding and also inspirational because this was one of the inspirations for this talk having worked with junior devs quite a lot it's one of these things that I've noticed is they really struggle with debugging and I think that's kind of because we don't really teach it as a skill it's one of those things that you sort of expect developers to just pick up naturally and there's so much there to learn if you really focus on that and that's why I decided to write this talk hopefully there will be something useful in here no matter how deep down this hole you've been before but err yeah so a quick look at the process itself how often have you actually spent time thinking about how you debug it's easy to forget that it's a difficult skill that it's it's something that you need to master in order to become a really experienced developer and it's learnt over time and improve with experience and it's not just about the tools you use but it's the mindset in the process and how you actually work through your debugging tasks and it becomes particularly clear when we compare those new developers with more experienced ones often new developers will jump straight into the code they'll go and change a whole bunch of things they won't remember what they've changed and what they haven't and what actually might have fixed the problem and what was maybe just some extra bit of code that they stuck in there that wasn't useful at all but it's something we do pretty much every single day and so in this talk I won't go into the detail of how important it is to reproduce the bug be methodical only change one thing at a time how to narrow down where the bug is but it's surprising how often the stuff is not taught so if you're a junior developer or you're teaching junior developers I hope you're one of either of these two things ya do spend the time really looking into this stuff with them so there is one step that I do want to cover really quickly because even the most senior developers I've worked with and including myself sometimes I forget to write tests like this is the first thing that you do right if you've discovered a bug write a test that reproduces it because it not only will keep your focus on just that one bug it'll also speed you up because you no longer need to launch your app and click about to get to the state of where your bug actually is and of course it'll help your bug can never return so let's move on to the tools starting with the console well the polls are in as you can see we've got 56% of developers on the left-hand side use console.log and 67 on the right-hand side and it's it's not surprising right because we've been conditioned to use it alongside simple text editors like sublime text atom notepad etc and a large portion of web developers have also just simply missed the exposure to a formal or Street or structured debugging process like myself and the browser consult is a pretty nice way to inspect the results of your logs so it works and and it's easy well why change it well because there is so much more so even if we just take a closer look at console Tarlac you'll see that there are lots of different ways to optimize it so here on top we have the normal console dot log usage for logging out these two variables pin 1 and pin - and here they yeah but on the bottom if you just add two extra cat characters to turn this log into an object yeah you not only get the results of the log but of the the value of the variable but you also get the variable context so it's much easier to see at a glance what you're logging it can be really useful especially when you're logging a lot of different things in your application and you can also really add easily add styling to your lives by including this percentage sign see at the beginning and then passing through some styling as the second parameter you can get really pretty colors so sticking to the console for now did you know that there are actually a whole bunch of different more methods on that object so I'm gonna show you my favorites but googling will reveal a hell of a lot more for instance console table is super useful if you want to log out an array of objects so here you can see it's much easier to kind of compare at a glance the different values and next we have console group which is when I don't know about you but have you ever ended up adding so many logs in your application that you can't tell which was the one that you just added well group and group collapse are really useful for structuring your logs and to collapsible groups creating less noise in the console for you to analyze which is really the aim of game another useful function you can use in the console is the dollar selector so it works similarly similarly to the jQuery selector it's an alias for the document selector function in the console if you include a 0 after it as I've done here you can get the most recently inspected HTML element or JavaScript object a 1 gets you the second most recently selected etc etc up to 4 super useful if you want to quickly see what properties or attributes are on the Dom node or JavaScript objects that you're looking at and if you use Dola Dola it's the equivalent of document query selector or even better it returns you a proper array rather than a node list so you can manipulate it straight away console dot trace has been a lifesaver for me especially when you're working in a new code base and you can't actually you don't have that you know inherent knowledge of what is calling what and so in here I added a consult up trace on this handle filter click function to figure out what was calling it and you can see that it's now telling me that it was called by a handle click in filter jeaious and consular is great when you want to inspect a Dom node as a JavaScript object rather than as its markup which is what console.log returns you so you can see all the properties on that Dom node much more easily and no though it's even more useful as you can see console logs let's spit out the objects in black and white and it only displays two levels deep consult order on the other hand allows you to add some really handy configuration so here we've just added this extra object where we've said colors true depth null and it means that we get logs or pretty with lots of different colors and you can now access the lat and long properties on that geo object so let's say we've been working with console functions for a while and want to step it up well let's dive into the diff tools so I'm going to focus on Chrome because it's what I'm most familiar with but the Firefox dev tools are also really great and have a lot of the same functionality browser dev tools have some really handy features for debugging so the dev tools debugger is the best one of them one of the simplest ways to activate this is by using a debugger keyword in your code so this debugger keyword I typed this in into my editor and opened it up in chrome and when I refreshed it hit the debugger keyword there at that break point and so now you can see sorry I'm having video issues as well but hopefully you'll be able to see that we can log out the value of the variables in scope at the moment we can also inspect the entire scope at this point of execution and we can also step through the code and speaking of stepping just in case you've never used a debugger before here are your main options they're pretty much the same no matter what kind of language you're writing or what kind of tool you're using first we have resume which is when you're on a breakpoint and you press this and you'll be able to resume the script until the next breakpoint is hit if you hold this button down you'll also have the option to play through without hitting any more breakpoints which can be useful when you just want to get the code running the next is step over which executes the next function after your breakpoint and stops afterwards and then we have the step into and out of functions and note that these are functions that we're stepping over into and out of not lines of code they can take a little bit to kind of get that and yeah so what we've been doing here is adding a line of code breakpoint with the debugger keyword in our IDE but if you set these breakpoints in the dev tools or in your editor you'll see where this can be much more efficient than using console.log it's almost as if you've peppered your whole code base with console logs without actually having to do so and having to clean anything up simply click on the line number so here I've clicked on 14 21 and 26 and then run your code as usual and the execution will stop on your set line of code break points which you can then press resume to hit the next one and go through as opposed to needing to step through or over every single function and when you're doing this you may also want to use a watch expression so that's what I've got here on the right hand side I've just decided to I've clicked the little plus button there and I've just decided to watch this dot state don't Mysteries because I want to see what's happening to that data and then as you step through the code that expression will update so you'll be able to see the value of whatever you're watching there are lots of different types of breakpoints and you can see these as sit these directly in the dev tools so for example example we've got the line of code which is what we've just been talking about conditional line of code which I'll show in a second daaamn so if a Dom node changes xhr so if you want to break on a particular HTTP request event listeners exceptions and functions so here on the left you can see how to add breakpoints just on certain event listeners so here just by ticking click there means that anytime I click on my app a breakpoint will be hit and then we have the Dom nodes so here I'm gonna break on when a Dom nodes attribute is modified and then conditional breakpoints down the bottom can be really useful for when a certain function say a scroll hander or a react render is called multiple times but you only want to stop execution when something has a certain value so here I'm creating a breakpoint that will only be hit if the length of my Mysteries array is more than zero so I here only want to stop when the API has actually returned my data because I only actually care about the data for this particular debugging case I know that the API is returning so I don't need to stop when the API hasn't returned but the react render is run so you can always click on the pause on exceptions button if you want a breakpoint when there's an error and the tick box to pause on court exceptions can be really useful for instance if you've got a try-catch that's swallowing your errors and you're not sure why then you can find out more about those exceptions when you have a bunch of breakpoints in your app it can be useful to disable one or more when you're focused on something specific so this check mark in the breakpoints list here will just disable that breakpoint temporarily and in the debugging toolbar you can disable all breakpoints in case you want to just check how your app runs while you're checking some changes you've made for example and a tool that's really useful when you're using the debugger is like boxing this lets us prevent the debugger from stepping into certain scripts when we're debugging code so here I was debugging a reaction lifecycle function and I jumped into the react Dom library I can be pretty sure that my bug is not in the react Dom library so I blackbox the script and this way next time I step through into a function that comes from this file the debugger will simply ignore it and I can focus on my application code you can also include file patterns in the dev tool settings - black box entire folders like node modules for example another useful trick when you're really unfamiliar with a code base is command + backslash if you press this shortcut when javascript is executing it will add a breakpoint to the code straight away and stop it executing you'll be able to instantly see what is happening the moment you press that shortcut and you can also not add log points and chrome dev tools which is essentially a console log that you don't have to remember to delete from your code the debugger won't pause on these points but you'll still get the results in the console another really useful tool when debugging and the dev tools is the snippets option under the sources panel here you can save your own code snippets to run in the console and there are some really great collections of snippets available online in different libraries so one of my favorites augments the console with a function called console dot save which you can use and pass anything to it which then gets downloaded as a JSON file this is really handy especially when you have a big JSON object that you want to open maybe in an IDE or you want to send it to a colleague for example another useful tool is live expressions you can click the I icon here to type something into the console and create a live expression this pins it to the top of the console and it updates real time it can be really useful when something in your code needs to respond to a window width or scroll position for example and you'll be able to see it update as you scroll down the side so what about when you want to actually test some of your bug fixing hypotheses well a really great feature in chrome is called local overrides so here we go to the sources panel and go to overheads and we can set them up by selecting a folder on in this case my desktop I think and [Music] we then need to give chrome access to that folder and then we can go and change any of the code on this site for example this part of the reddit website and add whatever we want so I'm going to add a background color of purple and now if I go come and save you can see I've got this little purple dot up here on the file and then when i refresh the changes I persisted which is really really useful if I close the dev tools and refresh the changes are gone this approach is really useful for making smallest changes to production websites when you're trying to debug something in particular when you want to fix something quickly and you have a reasonably good idea of where it is you don't need to have your local environment running you don't even have to have the original code on your computer this can be done with just about any computer setup so what happens when you want to go further and make bigger changes that you not only want to persist on browser refresh but persist to your own project file sitting locally on your computer well the diff tools also have a really interesting feature called workspaces so here's a little app I made for calculating insulin dosage for diabetics note it's a production app on Heroku not on my localhost so this could could be any website right so in the file system tab I can add the folder this is my actual folder on my desktop for this application and again give the dev tools access to it and now you can see my applications loaded here in the sources panel I'm gonna make a change I'm just gonna add a console log of hi why not and if I save that and go to my IDE you can see that the file itself has been updated and I can also go back the other way so I'm gonna add every one here and see that it's persisted here to the dev tools this could be super useful and really powerful and in fact for some people it allows them to use just the dev tools debugger as a sorry dev tools as their IDE however it can be a little flaky and it's still not as good as a full idea in my opinion in particular it struggles with more complicated build systems but if you have a project that you built with create react out or view so yeah CLA for example you can actually just drag the entire folder onto the sources panel and it's all set up for you so if you like this idea of being able to persist changes on your production website there's one last way I want to show you this is the concept of proxying your production files to local files on your hard drive similar to workspaces but without the dev tools persistence but with a lot more other features that better support complicated build systems the simplest is a Chrome extension called resource overrate so say you have a version of your application running on localhost using this extension you could proxy the call that your production website is making in this case on the left hand side bandolce is - the version of that file and on your local drive so that's my local host is and this allows you to change your code and test it within the larger environment where the bug actually occurred applications like fiddler and Charles proxy which is my personal favorite also allow you to do this but with a lot more features including the ability to monitor and inspect all the calls that your website is making I've been on teams that have literally used Charles proxy for their entire front-end development flow many big applications can be tricky to set up locally and trying to keep the backend architecture and api's up-to-date as people are working on them as well as your own front-end code base across multiple teams can be a pain in the ass that can take quite a lot of time if however you have a reliable staging environment that everyone's pushing to then proxying your front-end files is a nice way to skip that set up entirely so a lot of the technology I'm covering either is seriously enhanced by or doesn't work at all without source Maps so a source map is a file that allows the browser or other technology to map the compiled or compressed code back to its original file it's a really important tool that helps with debugging minified code is almost impossible to debug properly on the top we're inspecting a website without source man and you can see all the variables have met beam angles and the ESX class has been transposed whereas on the bottom source maps have been setup and it's way easier to understand what's going on because it's the code we actually wrote and depending on your build process it should be pretty straightforward to set up here's the config for web pack and at the top is the way to tell web pack to use its standard development configuration which includes source maps by default if you want more control you can define it separately I've chosen cheap module evil because I like the balance between speed and support but your choice will depend on your use case then beneath that we have the config for production and the only thing you actually need here is the dev tool property but if you're using uglify jeaious to minify your code you'll want to see it source map to true when you declare that plug-in and if you want to set the file name of the source map you can get to when you build your project you should see your source map file like we have over on the right hand side so what about deploying source maps to production well I am a big believer in doing this because production behaves when you really want to know what's going on you're in a hurry and you want to decipher the code pretty quickly so the good thing about source maps is that they only get downloaded when the dev tools are opened so then they have no effect on your application or on its performance and if you're really worried about people being able to look at your source code and a metaphor unhhhh minified and keep in mind that security through obscurity is never a good idea then there's a pretty straightforward solution so here you can indicate in the javascript file a source map your source mapping URL configurable with webpack that points to the source map that's been uploaded to a different location say one that's only accessible by your team like an s3 bucket maybe that's only set up for your company's VPN to access and if you're not able to setup source maps say you're just being nosy and checking out someone else's website you can always click on the format' button to make the code at least slightly more readable so moving on now to performance debugging and I do not have time to do it justice there's so much you can learn about here and it's easily another entire talk but I wanted to quickly illustrate where you could start and the key is to find the code that you wrote right so these flame charts to be a little bit indecipherable until you actually figure out where your code is so if you click to open the main panel you'll see all the activity that occurred on the main thread including the execution of JavaScript usually a lot of the stuff here is found in frameworks but if you scan through the orange sections you'll be able to find your JavaScript files which is usually what you're looking for right in this case it's my main J's file and know this is a very basic one page app which is why it's so small you can then zoom in further and find the functions in your app and compare the time that they're taking with each other here we can see a call to app in child and fetch which should be a little bit more familiar to us and the easiest way to debug in apps performance poor performance is by doing a performance audit with lighthouse this is a tool inside the audits panel here you can see the results on the same small one-page app and the best bit here is the opportunities section where they have a where you've got a list of the resources that you should optimize and it has specific details on how to do so the audits panel also allows you to order other things like accessibility which is really great it makes something so important it's so much easier and if you follow the expense the specific advice in the audit your app will be so much more usable for so many more people and in many cases improve the experience everyone keep in mind though there is no substitute for proper manual accessibility testing so when it comes to debugging specific elements for their accessibility the elements pane comes in handy here you can inspect elements and see which properties are correctly filled out so in this case we're inspecting a text input you can see that the name property is searched and this is what screen readers will read out when the user focuses on this input you can see that the name was computed by looking at the placeholder property this input should really have a proper label or an area label but at least it has a placeholder so all users would now be able to know what it's for rather than a screen reader just reading out text input so the last thing for the dev tools did you know that you can even debug node in the dev tools you just need to run your node script with the inspect flag BR came by the way it means break before the code starts so that you can add your breakpoints straight away then either click on this green node icon down here on the left or go to Chrome slash inspect and click on open dedicated dev tools for node if you like this workflow you should check out the node inspection manager extension which manages all your scripts and work and windows for you so let's get to the really good stuff integrated debugging in the editor has been around for ages but many JavaScript developers are either not aware of it they think it's too tricky to setup or they don't want to change their debugging mindset because they don't think it's worth it well I'll let you be the judge but do give it a go first unfortunately we have a lot more front-end editor options these days some of which include an inbuilt debugger I'm gonna focus on vs code because it's super light and fast and it's what I use every day and I promise I'm not trying to sell you anything because well that would be stupid because it's free but yeah other ideas like webstorm also include an inbuilt debugger and the idea is pretty similar I'm gonna take you through my debugging process and how I set it up with a mini front-end react app that talks to an express server I've added a couple of spelling mistakes to simulate a real bug that you might be trying to fix so typical process for debugging a front-end application might look something like this we open the browser we see an error in the console we go to our editor we log out some of the variables back to the browser and refresh or maybe a hot module reloading if we're lucky we've chosen a variable that helps us determine how to fix the bug back to the editor make the fix back to the browser refresh okay great perfect well that's a hell of a lot of guesswork and switching back and forth I mean we're we're used to it but but it doesn't need to be this way vias code has a bunch of extensions that let you debug tons of different languages in different configurations the most useful for us is the debugger for Chrome extension it's actually framework agnostic so you could be working with angular if you react whatever you like but I'm going to show you the configuration for my app so first of all I'm going to the extensions and searching for the debug of Chrome I'm going to install that and reload vs code and now I can go to configurations and add a new configuration and I'm gonna choose the launch Chrome one here and I'm gonna change the URL to localhost 3000 because that's what create react app uses by default and save that and then press play and you can see that the app is loaded there's absolutely no other setup or settings it's really really easy and the debugging experience it's also really nice so here I have a bug because there's supposed to be some quotes showing up in my app and if I add a debugging breakpoint about where I think that the bug probably is and then refresh I can see I've hit my breakpoint and I can see that QWOP is undefined I wonder why and if I go into the variables here and inspect the actual data I can see oh the data calls it quote okay well then I can go and edit the variable fix the bug remove the breakpoint and then restart and hey it's fixed and I didn't even need to touch the browser obviously this is a pretty fake example but you get the idea so before I finished I should just quickly mention that in no way have I covered the space I've obviously had to focus on one browser and one IDE and I didn't even touch on mobile and network and Service Worker debugging to name a few there is so much more to explore here and of course accurate and realistic test coverage is an extremely important and useful way to prevent bugs in the first place provide a quick and easy way to test fixes and prevent them from occurring again the golden rule my golden rule whenever you fix your bug make sure there's a test for it so the last thing I'm gonna leave you with is this if you want to stick to the good old console log then that's cool by me I still use a combo of different tools including console.log but please at least set yourself up with a good code snippet so you're not wasting your life typing it out by hand every single time that's it thank you [Applause]
Info
Channel: JSConf
Views: 13,698
Rating: 4.9439254 out of 5
Keywords: debug, console, debugger
Id: TtsvMRxmfGA
Channel Id: undefined
Length: 29min 18sec (1758 seconds)
Published: Tue Oct 22 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.