Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Semicolons after variable declaration [duplicate]

Tags:

javascript

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/

like image 497
Sam Braslavskiy Avatar asked Feb 11 '23 21:02

Sam Braslavskiy


1 Answers

This is because without the semicolon, the expression can continue onto the next line. It can help to understand if you remove the linebreak:

var A = function(){
    console.log('I am A')
}(function B(){
    console.log('I am B');  
})()

Here, you create an anonymous function expression, then call it with a single parameter (that's function B). You then call the result of that. However, your first function doesn't return anything, so it returns undefined. Then, you cannot call undefined (undefined is not a function).

However, a function block works differently. That cannot be called on the fly. Therefore, your second example works just fine.

You can read more on MDN:

  • Functions general reference
  • function keyword
like image 136
Scimonster Avatar answered Feb 14 '23 09:02

Scimonster