Immediate Functions in JavaScript – The Basics

JavaScript

JavaScript LogoFunctions are a very powerful feature in JavaScript; they provide modularity and scope. The immediate function, WHICH offers a heightened level of functionality, is an often overlooked feature of JavaScript

An immediate function is one that executes as soon as it is defined. Creating an immediate function is simple: you add the open/close parentheses after the closing curly bracket, and then wrap the entire function in parentheses. That’s it!

Example # 1:

In Example # 1, we have a very simple function. If you were to paste this function into your code and run it, nothing would happen. This is because the function is assigned to a variable, and that is it. We have only the function declaration here, but we never call the function. But if you were to add the line “myFunc();” to this code and run it, the output would be: “I am a simple function”.

Example # 2:

In order to turn this function into an immediate function, we add the open/close parentheses after the closing curly bracket and then wrap the entire function in parentheses. After we do this, we run the code and whatever happens in that function is executed immediately after the function declaration is complete.

So the output for Example # 2 would be: hello, I am an immediate function

Example # 3:

In Example # 3, we first declare a variable called “myName” before declaring our function. When declaring our immediate function, we take one argument: “thisName”. At the end of the immediate function declaration, the open/close parentheses pass the variable “myName” to our immediate function. So, not only does this set of open/close parentheses execute the function, it also allows you to pass an argument to that function.

The output for Example # 3 would be: “hello, my name is: bart Simpson”

Summary:

In this article, we touched on what immediate functions in JavaScript are, how to construct one, and how to pass parameters into them. But immediate functions in JavaScript can get very deep, very quickly. There is a world of power and subtlety that is available to you via immediate functions. Since that is out of the scope of this post, however, it will be covered in more detail in later posts.

Helpful Links for JavaScript Immediate Functions

http://nandokakimoto.wordpress.com/2011/05/17/javascript-immetiate-object-initialization/

http://stackoverflow.com/questions/939386/javascript-immediate-function-invocation-syntax

http://dreaminginjavascript.wordpress.com/2008/07/03/immediate-execution/