The good old fashioned way to debug like in any programming language is to use the browser console (for Java developers, this is them same as System.out.println()). Console is a really powerful and often underestimated tool which provides several useful methods.
- console.log(): Use this for simple logging of values. This statement prints the element in an HTML-like tree.
- console.dir(): Use this if you want to see the properties of a HTML element. This statement prints the element in a JSON-like tree.
- You can also use console.warning() or console.error() which will make your logs more semantically and visually clear.
- console.table() will display tabular data as a table which is useful for complex and long arrays and objects.
- You can actually provide more than one parameter for logging statements.
- Don’t use console.log(obj),
use console.log(JSON.parse(JSON.stringify(obj))). This way you are sure you are seeing the value of obj at the moment you log it. console.dir() seems to do the trick, too.
- There is also alert() which I am mentioning for the sake of completeness. You rarely should have to do this and you probably will need to remove these statements before deploying to production as alerts are quite annoying and web browsers will block them if you use them too often.
Use the console when the amount of logs is low and the code is not too complicated. You also might want to prevent some logs to be visible in production mode. Sensitive data should not be logged in production. Either delete these statements before deploying to production or use a plugin to disable logging.
Browser developer tools
Prefer this to spamming console statements if the code you want to debug is more complex and if you want to understand the execution flow. You usually open the developer tools in any browser by clicking Inspect element, by opening it from your browser menu or by performing a special keyboard command (e.g. pressing F12 in Chrome and Firefox).
You can set breakpoints visually by selecting the lines and see how your code runs through and how the state changes during execution.
One nice trick in Chromium-based browsers (e.g. Google Chrome, Opera; I’m just gonna mention Chrome from now on for brevity) is $0. When you select an HTML element in the Elements tab, Chrome assigns the selected HTML element to a variable called $0. You can print this out in the browser console with $0 or console.dir($0) to see the properties of the selected DOM element.
In Angular, you can make additional use of this feature and use:
to see the corresponding Angular component with all of its properties.
IDE & Editor debugging
Some IDEs like IntelliJ/WebStorm and editors like Visual Studio Code provide debugging tools, either built-in or by installing free plugins/extensions. For example, Visual Studio Code has a extension called Debugger for Chrome which enables developers to debug their code directly from the editor when using Google Chrome.