I've stumbled upon one very interesting gotcha, which was really hard to find. Since found, it was not hard to solve, but I'd like to find explanation in order not to repeat something similar in future. Here's a simplified version of my JS-code:
//the following does not work:
var A = function(){
console.log('I am A')
}
(function B(){
console.log('I am B');
})()
A();
I was expecting to see 'I am B', then 'I am A' in console. However, there was Uncaught TypeError: undefined is not a function
After a long debugging I have found out, that the missing semicolon just after A function causes the problem:
//the following works as expected:
var A = function(){
console.log('I am A')
};
(function B(){
console.log('I am B');
})()
A();
Moreover, when you declare the function in other way, everything will be just fine:
//this works too
function A(){
console.log('I am A')
}
(function B(){
console.log('I am B');
})()
A();
So, it's a combination of a variable declaration and parentheses that break the code.
Could you please explain why this happens?
Here's a fiddle for testing: http://jsfiddle.net/wxu2f8en/