TypeError with two consecutive self-executing anonymous functions

This question is based on the accepted answer here . Why TypeError following code snippet warn โ€œfirst,โ€ then โ€œsecond,โ€ then errors with TypeError ?

 (function() { alert('first'); }()) (function() { alert('second'); }()) 

This explanation is that the return value of the first function is trying to invoke a call. But why did this happen? [Also, why wasnโ€™t the semicolon inserted after the first do-it-yourself?]

+4
source share
3 answers

Without semicolons, it will evaluate:

 (function() { alert('first'); }())(function() { alert('second'); }()) 

The first function is executed, and since it returns nothing, it additionally evaluates:

 undefined(function() { alert('second'); }()) 

Then the second function is executed, and it returns undefined again, therefore:

 undefined(undefined) 

Which doesn't work, of course ( TypeError , since undefined not a function). Separate function calls must be separated by a semicolon, since each statement must be valid.

+5
source

ASI, automatic semicolon. Your code should have been written as follows:

 (function() { alert('first'); }()); //<--semicolon (function() { alert('second'); }()); //<--semicolon 

Instead, a step is taken here:

 (function() { alert('first'); }()) (function() { alert('second'); }()) //now, the interpreter guesses that you mean to concatenate the two (function() { alert('first'); }())(function() { alert('second'); }()); //it also inserts a semi-colon where it should've appeared at the end of the script //first function doesn't return anything === returns undefined undefined(function() { alert('second'); }()); //second function doesn't return anything === returns undefined undefined(undefined); //however, the braces stay, since they can also mean function execution 

undefined not a function, so it cannot be executed, so you get a TypeError.

+2
source

This happened because your program was analyzed this way. We could summarize the program as

  (some stuff) (some more stuff) 

And it is clear that this should try to call some stuff as a function. Of course, a semi-colon will fix the problem, and you were hoping that a colon insert would do this automatically for you. Without knowing the detailed insertion rules, I would simply say that nothing was inserted, because the rules are specially designed so as not to change otherwise clearly defined behavior.

Of course, you cannot consider this behavior to be "clear." But language rules never work well in any situation.

+1
source

Source: https://habr.com/ru/post/1387882/


All Articles