Is there a difference between a named IIFE and a function call of a name immediately?

Is there a difference between and IIFE

(function foo () { var var_of_concern; }()); 

and simple function

 function foo () { var var_of_concern; } foo(); 

The caveat that bothered me was that if I didn’t exit either IIFE or the function, would IIFE support memory longer?

+3
source share
1 answer

The opposite, although this is probably not a serious problem.

Both are not syntactically the same. The second declares the function and associates it with the local character "foo". This function will remain after calling the function.

The IIFE form is syntactically one expression. The second form includes two operators: a function declaration operator and an expression operator (function call).

How a function call processes local variable declarations has nothing to do with how the function object came about. If both functions in your example are the same, then there is no difference in how this space is allocated to local variables in the function call.

edit - the key difference is syntactic : the function keyword at the start of a new statement introduces a function declaration statement. This syntax form does not provide an immediate call. That is, it is:

 function hello() { // some code }(); // <---- ERROR 

is a syntax error.

When the function keyword is displayed in any other context (well, any valid context), it does not declare a function - it is a function description (or a function definition, I have to check the spec). This is all that can be part of an expression in JavaScript:

  5 "hello" false (2 + 5) (function() { alert("Hi!"); }) 

Note that the last example includes parentheses - this is usually done to "flatten" "Oh, look at the function declaration!" analyzer behavior. This opening bracket means that the function keyword is not displayed at the absolute start of the statement, so it is an expression for the function instance.

+6
source

All Articles