#JavaScript - Immediately Invoked Function Expression

Immediately Invoked Function Expression

MDN Immediately Invoked Function Expression

Immediately Invoked Function Expression or self-executing anonymous function is a function that executes immediately after it is interpreted.

Use cases:


var a = 5;

(function() {
  var a = 3;
// 3

The variables defined in this expression remains in its own local scope and thus doesn't modify or be affected by the global scope variables.


(function() {
  var localVar = 3;

localVar // Reference error

You will get a reference error if you try to access a variable defined within a immediately invoked function expression.

It can be used to create private variables or private methods for encapsulation and data hiding.

let counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  return {
    get: function() {
      return privateCounter;
    decrement: function() {
    increment: function() {

counter.get() // 0
counter.decrement() // -1
counter.increment() // 0
counter.increment() // 1
privateCounter = 5 // create a global scope variable called privateCounter
counter.get() // count is still 1

Associate an item in a loop with its respective item instead of the last item as the value is only assigned the function within the loop is called instead of when the loop is run.
<p id="help">Description will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
<p>Username: <input type="text" id="username" name="username"></p>

function showHelp(help) {
  document.getElementById('help').innerHTML = help;

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your email address'},
      {'id': 'name', 'help': 'Your first name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'},
      {'id': 'username', 'help': 'Pick a unique username'}

  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {

source: MDN Closure

The description p tag will always show 'Pick a unique username' no matter which input you select because when you set the input on focus, the loop had already finished executing and thus, i counter in the loop would be 3 and points to {'id': 'username', 'help': 'Pick a unique username'}.

One way to fix it is to use Immediately Invoked Function Expression.
for (var i = 0; i < helpText.length; i++) {
    (function() {
       var item = helpText[i];
       document.getElementById(item.id).onfocus = function() {
// Immediate event listener attachment with the current i of item when the loop is iterated. 

1) why-using-self-executing-function StackOverflow thread
2) What is the (function() { } )() construct in JavaScript?

Thank you for reading!