Breakpoints are a great way to debug JavaScript in the browser. You can pause the code at an arbitrary point, inspect the variables, test functions in context and resume script execution whenever you are ready. Debugging in the browser allows you to cut down on switching between your code editor and the browser and can make you more productive.
Chrome indicates a normal breakpoint with a blue highlight on the line number. However, you can also set a conditional breakpoint, which Chrome indicates with an orange highlight on the line number. A conditional breakpoint will only pause the script of the condition is met. This is particularly useful when you have a loop in your code and you only want to pause the code when a value is of a specific type (e.g. undefined) or within a specific range.
However, there are times when you may want to log a value on each iteration of a loop. Typically, you would go back to your code editor and enter a console.log()
, which you may then forget to remove. As we know, a stray console.log()
in your script could go into production and prevent your script from running in certain browsers. What if we could log the value without editing our source code or leaving the browser? Well, you can!
To log JavaScript values directly from the browser in Chrome, just right click on the line number and select ‘Add Conditional Breakpoint’. Then, instead of entering in a conditional, just type console.log()
and pass in the variables for which you want to log the values. There you have it! This is a great way to debug issues in production without having to constantly deploy updated code.