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.