Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

info

My home for all the weirdities of javascript

Self Executing - Anonymous Functions

I never understood these until I read an article by Mark Dalgleish

Consider this tiny piece of code

Anonymous functions
(function(){
  console.log('Hello World!');
})();

The above is a self executing block of code or a closure in javascript speak (not to be confused with a closure in Delphi or C++).  The magic here only happens because of the () at the end of the expression.  If you remove the (), the block does not self execute.

You can pass parameters to the ending (), these should match any parameters expected by the function() declaration see the following example

(function( x, y ){
  console.log(x + y);
})("Hello world", 52 );

When this executes the output will be Hello World52.  

I was trying to work out what was the advantage of this model over just writing a number function that could be called from anywhere because as a self executing function it can't be called from anywhere at anytime.  

According to MDN (Mozilla Developers Network) info on Closures, "closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created."

So the following piece of code demonstrates this quite nicely

example js code
function init() {
    var name = "Mozilla"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

The function displayName() declared at line 3 is a closure, notice that it has access to it's enclosing environment.  When you run this code, the alert displays the message "Mozilla".  The function displayName() is able to access the variable name (line 2) because of what javascript terms lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.


  • No labels