DEV Community

Discussion on: Tell me a bug story

Collapse
 
lexlohr profile image
Alex Lohr

I once wrote a limited JS parser to remove comments and stitch different JS files together into one bundle in PHP (that was before grunt, gulp and webpack or even node.js or AST-based JS transpilers. Yes, I'm that old). Somehow, it broke the code of one of our applications and I had a hard time figuring out where this happened.

First, I made sure that nothing but comments had been removed, but everything was correct on this account. Then, I had a closer look at the bug.

TypeError: undefined is not a function

So I searched the whole code for calls of variables that could in some circumstances not contain a function. Again, without any result. After long hours of searching fruitlessly, I had a coffee and try to look at the problem from a new perspective and suddenly, like clouds indiscernibly shifting forms, I saw the issue.

In two of the files, we had encapsulated our code in an IEFE (immediately executed function expression) not to leak variables into the global scope and forgot a semicolon after the first one. The resulting code went like that:

(function() { ... })()
(function() { ... })();

Do you see it, too? The opening parentheses of the second IEFE were interpreted as a call of the assumed function returned by the first IEFE (which of course returned undefined). I introduced a small filter into my parser that made sure that any IEFE would be terminated with a semicolon so that this error should never ever happen again.