0

While trying to understand closures in JS,I came across the following code:

  var add = function () {      
    var name = "xyz";
    return function ()
      {
        return name;            
      }          
  }
  ();    

I am unable to understand the purpose of () at the end of the function.

Using console.log(add()); gives xyz as the output.

But when I remove the () from the end of the function, I am getting [Function] as the output.

Ayan
  • 8,192
  • 4
  • 46
  • 51
  • is the normal sitax declaration for a function .. – ScaisEdge Jan 19 '17 at 15:17
  • it's the normal syntax for a function call – Oriol Jan 19 '17 at 15:19
  • it is a javascript self invoking anonymous functions http://markdalgleish.com/2011/03/self-executing-anonymous-functions/ – GibboK Jan 19 '17 at 15:21
  • 1
    If `function f(){}` is a function definition and `f()` is a function call, then `function f(){}()` is the same function call with inlining the function definition (simply substitute`f` with the definition). – Felix Kling Jan 19 '17 at 15:22

0 Answers0