Skip to content Skip to sidebar Skip to footer

Difference Between A Named Iife And Calling A Name Function Immediately?

Is there any difference between and IIFE (function foo () { var var_of_concern; }()); and a plain function function foo () { var var_of_concern; } foo(); The caveat that c

Solution 1:

The opposite, though it's probably not a serious concern.

The two are syntactically not the same. The second declares a function and binds it to the local symbol "foo". That function will remain after the function call.

The IIFE form is syntactically a single expression satement. The second form involves two statements, a function declaration statement and an expression statement (the function call).

The way that a function call handles local variable declarations has nothing to do with how the function object came into being. If both functions in your example are the same, then there's no difference to how that space is allocated for the local variables in a function call.

edit — the key syntactic difference is this: the keyword function at the start of a new statement introduces a function declaration statement. That syntactic form does not provide for immediate invocation. That is, this:

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

is a syntax error.

When the function keyword appears in any other context (well, any valid context), then it's not a function declaration — it's a function instantiation (or function definition; I'd have to check the spec) expression. These are all things that can be part of an expression in JavaScript:

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

Note that the last example involves parentheses - that's commonly done to "defuse" the "Oh look a function declaration!" behavior of the parser. That opening parenthesis means that the function keyword does not appear at the absolute beginning of the statement, so it's therefore just a function instantiation expression.

Post a Comment for "Difference Between A Named Iife And Calling A Name Function Immediately?"