06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Functions, Closures, and Modules<br />

In the bar() function, we are inadvertently modifying the value of i=2. When we<br />

call bar() from within the for loop, the value of the i variable is set to 2 and we<br />

never come out of an infinite loop. This is a bad case of namespace collision.<br />

So far, using functions as a scope sounds like a great way to achieve modularity and<br />

correctness in <strong>JavaScript</strong>. Well, though this technique works, it's not really ideal.<br />

The first problem is that we must create a named function. If we keep creating such<br />

functions just to introduce the function scope, we pollute the global scope or parent<br />

scope. Additionally, we have to keep calling such functions. This introduces a lot of<br />

boilerplate, which makes the code unreadable over time:<br />

var a = 1;<br />

//Lets introduce a function -scope<br />

//1. Add a named function foo() into the global scope<br />

function foo() {<br />

var a = 2;<br />

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

}<br />

//2. Now call the named function foo()<br />

foo();<br />

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

We introduced the function scope by creating a new function foo() to the global<br />

scope and called this function later to execute the code.<br />

In <strong>JavaScript</strong>, you can solve both these problems by creating functions that<br />

immediately get executed. Carefully study and type the following example:<br />

var a = 1;<br />

//Lets introduce a function -scope<br />

//1. Add a named function foo() into the global scope<br />

(function foo() {<br />

var a = 2;<br />

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

})(); //

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

Saved successfully!

Ooh no, something went wrong!