advanced debugging in javascript - prototype modification.

Sometimes regular methods of debugging just don't cut it. no amount of debugger breakpoints, console statements, or intense staring will reveal the bug. so, I'm going to do a series of quick posts of some advanced debugging techniques that I've learned over the years in javascript.

this time, I'm focusing on prototype mods. objects in javascript all have prototypes that dictate how they work. any method that is part of a constructor object is typically part of its prototype. for a basic example, substring can be referenced as String.prototype.substring. I know I'm simplifying it but this is supposed to be a short post.

so, how do you use this for debugging purposes? here's a scenario: you're using some internal javascript method, such as Storage.setItem to put things in local storage. when you look in localstorage, though, it seems that the storage api is messing with your data. you want to know why your data storage isn't being handled correctly. so here's what you can do:

Storage.prototype.setItem = (key, value) => {
console.trace(key, value);
console.log({ [key]: value });
window.localStorage[key] = value;

see how simple this is? all you have to do is rewrite the function so that you can "see inside" it, without messing up the core functionality. this style of debugging will work with any javascript prototype method. the technique can be applied quite easily in a variety of situations.

the only caveat is that you need to know exactly what the original function did in order to replicate the behavior. when I was debugging minerva's akasha, I wrote the above prototype override after reading the web storage spec to make sure I knew what I was doing by modifying it. and yes, this particular example is simple enough that I probably could have done it without looking at any docs, but it's good to be sure.

for those curious, here's the bug I was dealing with.

currently listening to:

- mother by florence and the machine

- sound chimera by laur

- hell is real by black dresses