JS concatenation clash

2009-12-09

Here's a subtle problem you might encounter when dealing with concatenated javascript files.

Say you have two files. In both files you declare the same function by name (this is important, don't use anonymous functions). You might find the page will behave differently when the files are concatenated, opposed to not. Here's how.

Say you have file1.js and it contains this:
Code: (JS)
function x() { alert(5); }
x();
Now say you have file2.js and it contains this:
Code: (JS)
function x() { alert(6); }
x();
What do you think happens? Well duh, first 5 gets allerted and then 6.

Now look what happens when you try this:
Code: (JS)
function x() { alert(5); }
x();
function x() { alert(6); }
x();
What do you think happens? You're probably going to guess it at this point, so indeed, 6 is alerted twice. So what's going on here?

It's all about processing and named functions. When you create a function by name (using the "function x()" syntax), the Javascript interpreter will actually parse those functions ahead, before the actual execution. It doesn't mind parsing a function who's name has already been used so it will happily replace the first instance of x by the second. So by the time the first x(); is executed, it will be the second x function and that's why you get 6 twice.... :)

Note that you can circumvent this by using anonymous functions...
Code: (JS)
var x = function(){ alert(5); }
x();
x = function(){ alert(6); };
x();
(Even if you use var twice)

Hope it helps ya! :)
Thanks to inimino for alerting me to this problem.