1. Technology

JavaScript By Example

Using Functions: 2. Self Invoking Functions

By

Another way of using an anonymous.function is to define the function and then run the function straight away. When the function is run as soon as it is defined you don't need to name the function or assign it to a variable in order to be able to reference it later because the function is only being run the once immediately after it is defined.

A self invoked anonymous function differs from running the same code without wrapping it in a self invoked function in one very important way. When you define variables outside of functions those variables have global scope and can therefore potentially be updated by any JavaScript in the page with the potential for conflicts with the same variable being used for two or more different purposes in different parts of the page. Functions limit variable scope in JavaScript so by placing your code inside a function you limit the variables to within the function and remove any possibility of conflicts with another variable of the same name elsewhere in the page. Since we are using the function to limit the scope of variables we only need to run it the one and so using a self invoked function means making the least changes to our code.

In this example wrapping the code in a self invoked function moves the five variables the script uses out of the global scope and limits their use to just this piece of code.

Note that we must wrap an anonymous function that is not being assigned to a variable inside of () as when the word function appears at the start of the statement JavaScript assumes that we are trying to define a named function and so would generate a syntax error if we didn't have the ( in front of the word function. The ) immediately after the } that ends the function completes the extra wrapper around the function and the extra () on the end is what invokes the function straight away.


(function() {
var num, lst, nxt, fib, i;
num = window.location.search.substring(1);
fib = '1';
lst = 1;
nxt = 0;
for (i = 1; i < num; i++) {
lst = nxt;
nxt += lst;
fib += ',' + nxt;
}
document.getElementById('ex').innerHTML = fib;
})();

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example
  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Using Functions
  7. JavaScript by Example: Using Self Invoking Functions

©2014 About.com. All rights reserved.