06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2<br />

The (function foo(){ }) statement as an expression means that the<br />

identifier foo is found only in the scope of the foo() function, not in the outer<br />

scope. Hiding the name foo in itself means that it does not pollute the enclosing<br />

scope unnecessarily. This is so useful and far better. We add () after the function<br />

expression to execute it immediately. So the complete pattern looks as follows:<br />

(function foo(){ /* code */ })();<br />

This pattern is so common that it has a name: IIFE, which stands for Immediately<br />

Invoked Function Expression. Several programmers omit the function name when<br />

they use IIFE. As the primary use of IIFE is to introduce function-level scope, naming<br />

the function is not really required. We can write the earlier example as follows:<br />

var a = 1;<br />

(function() {<br />

var a = 2;<br />

console.log( a ); // 2<br />

})();<br />

console.log( a ); // 1<br />

Here we are creating an anonymous function as IIFE. While this is identical to the<br />

earlier named IIFE, there are a few drawbacks of using anonymous IIFEs:<br />

• As you can't see the function name in the stack traces, debugging such code<br />

is very difficult<br />

• You cannot use recursion on anonymous functions (as we discussed earlier)<br />

• Overusing anonymous IIFEs sometimes results in unreadable code<br />

Douglas Crockford and a few other experts recommend a slight variation of IIFE:<br />

(function(){ /* code */ }());<br />

Both these IIFE forms are popular and you will see a lot of code using both these<br />

variations.<br />

You can pass parameters to IIFEs. The following example shows you how to pass<br />

parameters to IIFEs:<br />

(function foo(b) {<br />

var a = 2;<br />

console.log( a + b );<br />

})(3); //prints 5<br />

[ 55 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!