JS: semicolon after variable declaration

I came across one very interesting game that was very difficult to find. This has not been easy to solve since it was found, but I would like to find an explanation so as not to repeat something like this in the 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 expected to see "I am" and then "I am" in the console. However Uncaught TypeError: undefined is not a function

After a lot of debugging, I found that the missing semicolon right after A was causing the problem:

//the following works as expected:
var A = function(){
    console.log('I am A')
};
(function B(){
    console.log('I am B');  
})()
A();

      

Also, when you declare the function in a different way, everything will be fine:

//this works too
function A(){
    console.log('I am A')
}
(function B(){
    console.log('I am B');  
})()
A();

      

So this is a combination of variable declaration and parentheses that breaks the code.

Could you explain why this is happening?

Here is a fiddle to test: http://jsfiddle.net/wxu2f8en/

+3


source to share


2 answers


This is because without the semicolon, the expression can continue to the next line. This can help you figure out if the line has been removed:

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 one parameter ( function B

). Then you call the result. However, your first function returns nothing, so it returns undefined. Then you cannot call undefined (undefined is not a function).



However, the function block works differently. It cannot be called "on the fly". So your second example works great.

You can read more about MDN:

+5


source


You need to understand the difference between a function expression and a function declaration . Function expressions can be called immediately, which is why your first anonymous function is called passing function B as a parameter. Also, your first function does not have a return statement and therefore returns undefined (which is clearly not a function).



JS has an auto semicolon feature that you shouldn't rely on. Use a tool like JSHint to help you write code that is less error prone.

+1


source







All Articles