Skip to main content

Debug in JavaScript

· One min read

debugger

In browser, debugger can trigger breakpoint

debugger;

Debug native function

function debug(fn) {
// Arrow function () => {} cannot be used,
// Because `this` needs to be bound
return function () {
debugger;
return fn.apply(this, arguments);
};
}

To debug "string".at()

String.prototype.at = debug(String.prototype.at);

To debug console.log()

console.log = debug(console.log);

Inject function

Inject a function before the target function

function inject(to, fn) {
return function () {
fn.apply(this, arguments);
return to.apply(this, arguments);
};
}

To log the call stack and arguments when "string".replace() is called

String.prototype.replace = inject(
String.prototype.replace,
function () {
console.trace();
console.log(arguments);
}
);

"abc".replace("a", "s");

Call stack trace

Get the call stack

new Error().stack

Print the call stack

console.trace();

console.trace("message");

Debug in node.js

node --inspect server.js