Please help me to understand encapsulation

I just can’t get this concept . Please try to explain it in your words . What is the difference between

var x = function (){

//some code .........
}

and

var x = (function(){


//some code....................
}();

What is the exact definition of IIFE . I just know formal definition of IIFEE but can’t fully grasp it. Please show me the path.

The difference is one is immediately invoked, the II of IIFE. The parenthesis at the end of the function is executing it.

calculateSum(num1, num2) {
  return num1 + num2;
}

calculateSum(2, 3);

In this example, calculateSum is executed with values 2 and 3. Adding the parenthesis is telling your function to execute.

A useful reason this is used, you can see it in jQuery, is any variables you name won’t collide with other variables. Sometimes this is called the module pattern. If you use myNum a lot, but so did other libraries of code you pulled in, things would break. IIFE prevents that.

Thanks for your reply. You explained well IIFE concept. I’ve one more question .
According to you what should be the output of this function

   var x = 20;
    var add = function (a) {
         return x + a;
    }
    add();

The output would be NaN, not a number. If you replaced that with this:

   var x = 20;
    var add = function (a) {
         return x + a;
    }
    add(3);

you would get 23. The reason being that a is not defined, so you tried to add undefined + 20 and got NaN.

1 Like

Oh yes. I see. Please see it once

var test = function(){

   var x = 20;
    var add = function (a) {
         return x + a;
    }
    add(3);
}

when I am calling this function using test() in dev tool . It’s returning undefined. Why is this happening

Try this. Nothing is returned from test() since we are not returning the results of calling the add() function.

var test = function(){

   var x = 20;
    var add = function (a) {
         return x + a;
    }
    return add(3);
}
1 Like

Oh ! Thank you so much . Now I get it :slight_smile: