Javascript Self Invoking Functions

In this article, I will discuss self-executing or self-invoking functions of javascript and their hidden power with real-world example. We will also see why using setInterval is bad in some situations and should be avoided. Let’s explore little used but extremely powerful self-invoking functions of javascript.

Self-Invoking Anonymous Function

A self-invoking anonymous runs automatically/immediately when you create it and has no name, hence called anonymous. Here is the format of self-executing anonymous function:

(function(){
 // some code…
})();

You must be aware of the fact that javascript functions run immediately when you put () after their names eg:


doStuff(); // this will run immediately

And:


doStuff; // this will not run immediately and can be used as callback

Now because () exist at the end of self-executing anonymous function above, it will run immediately.

Interestingly, if you look at the source code of jQuery, you will see that everything is wrapped in between:

(function( window, undefined ) {
 // jQuery code
})(window);

That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window).

Notice that you can also write self-executing anonymous function like this:

(function(){
 // some code…
})();

Using extra braces like before function keyword is simply coding convention and is used even by famous javascript libraries such as jQuery and also recommended by Douglas Crockford. If you are confused about that extra pair of braces, here is another easy to remember notation:


! function(){
// some code…
}();
Notice the addition of ! before function keyword, it is essentially same in functionality to previous notation and also recommended (used by twitter too), quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

Self-Executing Function

Self-Executing function is a named function that runs immediately. Example:


(function foo(){
 // some code…
})()

Notice that now that we have named our function foo, it is not an anonymous function though it still is self-executing function because of () at the end.

How do they run automatically?

This can be best explained through an example. Let’s say in your webpage you have this javascript code:


function showUp(){
 alert(’Hello There’);
}

When you visit the page, the showUp function will not get triggered unless you do so by calling the function:


function showUp(){
 alert(’Hello There’);
}

// run the function
showUp();

However, you can make the function auto-run by making it self-executing function like this:

(function showUp(){
alert(’Hello There’);
})()

Where to use self-executing functions?

One obvious situation is when you want to auto-run a function like I showed in above example but that is trivial. If you are in a situation where you want to run a piece of code repeatedly like updating something in the database based on user interaction or fetching records from database every 10 seconds or you want to load new stories via ajax similar to how facebook does on its homepage or some other similar situation, one would normally go for setInterval function something like this:

setInterval(doStuff, 10000);

Above, doStuff function will get called every 10 seconds. That is the normal approach most developers seem to go with. However, there is a huge problem with that. The setInterval will call doStuff function exactly at specified time of 10 seconds again and again irrespective of whether doStuff function actually finished doing what it is supposed to do. That is bad and will certainly get you into unexpected results.

That is one example of where setInterval is ^bad^ and should be avoided.

This is exactly where self-executing functions come in handy. We can do the same task with the help of self-executing function along with setTimeout like this:

! function foo(){
 // your other code here

setTimeout(foo, 10000);

}();

This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using setInterval in this situation.

You can see the example in action here.

Another more common use of self-invoking functions is data privacy, everything wrapped in them is only available within the scope of these functions.

Free Admin Template

While working on a website or your custom CMS, you need to have an admin template and if you are already provided with one by designer or anyone, that’s good but sometimes you don’t have that option or you want to work on your personal project for which you need the admin template but designer isn’t available or you don’t want to buy an admin template or hire a designer. I often come across this requirement where I need an admin template which should have these features:

  • Easy to customize
  • Slick and nice looking interface
  • Can be modified to as many links as needed, suitable for small to big websites
  • Nice button and form styles
  • Nice looking info messages
  • Can be used as admin for any kind of website

Today I share with you guys an admin template that I created for my personal use. That’s free, you can use it for personal or commercial use.

Screenshots:

This slideshow requires JavaScript.

Download

Outputting PHP To Browser Console

Although there exist classes for outputting PHP to browser console such as Google’s PHP Console and certain others, I was looking for a way to output PHP to browser console without including those classes in my PHP files or installing any browsesr plugin to do the same. Currently, I am working on facebook application development in which you have to commit/upload the code to check certain output out of PHP unlike offline development where you check the code output before committing it up. This makes facebook application development a longer process for a developer but you got to live with it because you don’t have a choice.

Anyways, to speed up the code output checking process a little and rather using debug_backtrace, print_r, print/echo, var_dump, etc which you need to remove/comment again, I created a function to get output of PHP on the browser console. One could use error_log function but even that makes you go to your log file and then see the output. Of course, browser needs to support/have the console so that code result is output there. Because IE less than 8 doesn’t have console, this won’t work in IE less than 8, though result won’t be affected in it. Notice that you can see console in IE=>8 by pressing F12 key and then going to Script tab where you need to make sure Console tab is selected on the right side.

Here is the function:

     /**
     * Logs messages/variables/data to browser console from within php
     *
     * @param $name: message to be shown for optional data/vars
     * @param $data: variable (scalar/mixed) arrays/objects, etc to be logged
     * @param $jsEval: whether to apply JS eval() to arrays/objects
     *
     * @return none
     * @author Sarfraz
     */
     function logConsole($name, $data = NULL, $jsEval = FALSE)
     {
          if (! $name) return false;

          $isevaled = false;
          $type = ($data || gettype($data)) ? 'Type: ' . gettype($data) : '';

          if ($jsEval && (is_array($data) || is_object($data)))
          {
               $data = 'eval(' . preg_replace('#[\s\r\n\t\0\x0B]+#', '', json_encode($data)) . ')';
               $isevaled = true;
          }
          else
          {
               $data = json_encode($data);
          }

          # sanitalize
          $data = $data ? $data : '';
          $search_array = array("#'#", '#""#', "#''#", "#\n#", "#\r\n#");
          $replace_array = array('"', '', '', '\\n', '\\n');
          $data = preg_replace($search_array,  $replace_array, $data);
          $data = ltrim(rtrim($data, '"'), '"');
          $data = $isevaled ? $data : ($data[0] === "'") ? $data : "'" . $data . "'";

$js = <<<JSCODE
\n<script>
     // fallback - to deal with IE (or browsers that don't have console)
     if (! window.console) console = {};
     console.log = console.log || function(name, data){};
     // end of fallback

     console.log('$name');
     console.log('------------------------------------------');
     console.log('$type');
     console.log($data);
     console.log('\\n');
</script>
JSCODE;

          echo $js;
     } # end logConsole

Here is an example of how to use it:

$name = 'sarfraz';

$fruits = array("banana", "apple", "strawberry", "pineaple");

$user = new stdClass;
$user->name = "Sarfraz";
$user->desig = "Sr. Software Engineer";
$user->lang = "PHP";

logConsole('$name var', $name, true);
logConsole('An array of fruits', $fruits, true);
logConsole('$user object', $user, true);

Above code will result in what is shown in the image above. Although this does not prevent committing code first to see the code output if you are on facebook application development but it defintely does save some time. I have been using this function successfully so far, please let me know your ideas if any on how to improve this piece of code further. Have fun !