The very, very, very basics, but here are some tips:
- Use
console.log({ a, b })
instead ofconsole.log(a, b)
; - Use
console.dir()
to display a list of properties of an Object, e.g.console.dir(window.location)
. - Use
console.table()
for Objects or Arrays.
And check the console documentation on MDN.
The easiest way to debug your JavaScript code is by adding a debugger
statement. When the debugger is invoked, execution is paused at the debugger statement.
const toggle = (el, show) => {
if (typeof show === 'boolean') {
el.hidden = show;
} else {
el.hidden = !e.hidden;
}
debugger; // the browser pauses execution here
return el.hidden;
}
You can now step thru the code.
- Resume (
F8
orF5
in VS Code). - Step over next function call (
F10
). - Step into function call (
F11
). - Step out of current function (
Shift + F11
).
Watch the values of expressions change over time. This is especially valuable in the case of (reactive) state or data.
Directly add breakpoints to your code in the Sources
(Chrome) or Debugger
(Firefox) panel. When you are working with transpiled or minified code, you have to enable source maps
maps in the build step!
These work simarly as breakpoints with the exception that they don't pause execution and log the output of the expression in the console.
You need to install the following extension for your browser(s):
Then you need to add a launch configuration
.
{
"type": "firefox",
"request": "launch",
"name": "Launch: Firefox",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}/src"
}
Now you are ready to start debugging from within VS Code.
The Node.js script has to be running with the --inspect
enabled. The default debugging host and port are 127.0.0.1:9229
, but you can easily change this e.g. node --inspect=0.0.0.0:9230 script.js
.
You probably don't want to debug internal Node.js scripts or node modules, so you can add the following to the launch configuration:
"skipFiles": [
"<node_internals>/**/*.js" // 'magic name' for built-in core modules of Node.js
"${workspaceFolder}/node_modules/**/*.js",
]
Open Chrome and enter chrome://inspect
in the search. This will open the DevTools and will search for remote targets that are debuggable (--inspector
flag). Choose a target and this will open the dedicated DevTools for Node
.
ndb is an improved debugging experience for Node.js, enabled by Chrome DevTools
Use ndb
instead of node
command to run a script and you will get a full-blown Chromium debugger.
npx ndb server/app.js