Functions with names versus anonymous functions

Anonymous functions are not really as anonymous as they look at first sight.
Take for example the following function:

var x = function () {
  return 10;
};

Is this an anonymous function or is it a function named x?

The answer is both. Actually this is a variable named x that points to an anonymous function.

There is no difference between x = 5; or x = “tony”;, or x = function() {…

All these are variable assignments. As a matter of fact if we fire up our Chrome/Opera/Epic consoles ( CTRL SHIFT j) we can test it.

  1. Paste the above function into the console.
  2. Then type x;  to see what it prints out: It prints out the anonymous function explicitly.
  3. Now make this function a self-invoking function by adding a pair of parentheses to the end of it:
    var x = function () {
      return 10;
    }();
    
  4. Let’s check what x is assigned to by typing x;
    Now x is assigned to 10, not to the function itself but to the end result of function execution.So when we look at functions as their end result assigned to some variable suddenly they start to make more sense.

I go into more detail about self-invoking function on my latest eBook:
JavaScript innerHTML: A Project in Three Acts (Small Projects for Mastering JavaScript)

Tony

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s