Reputation: 2783
I came across following code. Can someone explain it to me? I'm not sure how it'll be executed? Is there any specific reason to write it like this?
var foo = (function() {
// ...bunch of code
return function(param1) {
// ...bunch of code
return var1;
}
})();
EDIT: I know that the outer part (...)();
, is executed immediately. What I'm not sure is why it is assigned to variable foo
. I guess when the IIFE is executed it'll only execute the return ...
inner code. But when the code inside that inner function ...
is executed? When the line return var1
is executed? I hope now it is clear as water
Upvotes: 0
Views: 961
Reputation: 6922
What you're seeing is a JS idiom called Immediately-invoked function expression. Extracted from Wikipedia:
An immediately-invoked function expression (or IIFE, pronounced "iffy"1) is a JavaScript programming language idiom which produces a lexical scope using JavaScript's function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function. This concept has been referred to as a self-executing anonymous function,[2] but Ben Alman introduced the term IIFE as a more semantically accurate term for the idiom, shortly after its discussion arose on comp.lang.javascript
As can be read in the extract, it's main purpose is mainly to avoid polluting the global namespace though it is also heavily used to take advantage of closure.
UPDATE
In Javascript, functions are first-class objects. This means that they can be passed around like any other object would be. They can also be assigned to variables.
The function you mention is just returning a function (like it could be returning an int or an object literal) that gets assigned to the variable foo
. foo
then has the reference to the function and can be executed like any normal function would be (i.e foo('a') ).
By the way, a function that returns another function or takes one or more functions as arguments is called higher-order function.
Hope this clarifies things.
Upvotes: 1
Reputation: 2542
The reason would be difficult to guess, but it could be for obfuscation, to avoid plagiarism
The execution will go like:
var foo will receive the result of a function call (the parenthesis after the assignment contain a function declaration, and right after those, the other pair of parenthesis are those function arguments)
that 1st anonymous function will execute the bunch of code, then return what the other function evaluates
the 2nd anonymous function well execute the other bunch of code and finally return var1
ergo: it is the same of executing bunches of code, store the result in var1 and then var foo = var1
, simplifying for explanation purpose
Upvotes: 0