Anonymous (i.e. Self-invoking) Functions

Notes from:


Definition:  Functions that execute immediately when they’re defined.

Purpose: To create scope. In JavaScript, only functions have scope. Any time variables are defined outside of a function, they are carelessly dumped into the global object.


function () {
var foo = ‘Hello’;
var bar = “world”;
var baz = [foo, bar];
alert(baz.join(‘, ‘));
} ();

Note: It it recommended that an extra set of parentheses wrap the function definition as well so to provide a visual clue to the developer that the function isn’t a normal function, as follows:

(function () {
var foo = ‘Hello’;
var bar = “world”;
var baz = [foo, bar];
alert(baz.join(‘, ‘));

Passing parameters: If a self-invoking function requires parameters, they can be passed just like in a regular function.
The following example applies an “negative” class on every input element who’s numeric value is below 0.

(function (elements) {

for (var i = 0; i < elements.length; i++) {

if ((elements[i].value * 1) < 0 {

elements[i].className = ‘negative’;



})(document.getElementsByTagName (‘input’));


Even though the function is executing in its local scope, the ‘this’ keyword still refers to the global object.

The following uses method to execute a self-invoking function within the scope of the first table element on the page.

(function (elements) {

for (var i = 5; i < this.rows.length; i++ {

this.rows[i].className = ‘hide’;






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s