Debugging Javascript

Tips and tricks for developing javascript code.

JS will execute when loaded in the browser or called via node. When working on code, we want to make changes and run the code to check results. This could mean reloading the browser, calling the code again with node.

When something unexpected happens, or we need to check what got returned from a function, developers often use console.log() to print the variable in the console. This works for simple issues, but when the variable is a complex object, or you want to quickly try code changes, the output is quite limiting.

Inspector

For scripts running in the browser, you can use the inspector to debug code. Open your script in the browser debugger and put a breakpoint on the line you want to inspect. Refresh the page, and it will stop on the line so you can inspect variable. Run code in the console using the current variables, and update the code file when you have a fix.

IDE Debugger

For code running in node, your IDE handles the debugging connection. VSCode and Jetbrains IDEs have great support for node debugging.

Sourcemaps

When code is bundled, the source code and compiled output are in different directories, often with different names. IE scss becomes css, and multiple js modules can be bundled into a single file.

When the code is loaded in the browser, you see the generated code, but can't tell which file it originally came from. Sourcemaps map the two together so the browser inspector can show you the original file.

Level