That title is a mouthful, but I wanted to make sure to identify this syntax properly as we've all seen them, but probably didn't understand what they were.

You might notice these self-invoking functions in 3rd party functions or jQuery plugins, as they are generally used by more seasoned developers. Okay, so what do they look like?

(
  function(intro, name) {
    var output = intro + ', ' + name;
    document.write(output);
  }
) ('Hello', 'Bob')

Looks kinda like we wasted 4 lines of code! But, if you're familiar with variable scope in JavaScript, you'll understand that what we actually did is avoid creating a global variable. Specifically, we did not declare the output variable in a global scope.

Any variable created inside a function is owned by that function, and hence destroyed (set to undefined) once execution of the function is complete.

So, although we have a few extra lines of code, it may be worth it, as it makes your code a little less complex by reducing the number of global variables.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *