What is a closure in javascript

Once, I was asked in an interview, how to define a closure in Javascript. I was lost at that time. I thought it was somehow like an anonymous function.

I was wrong. It turns out that I hadn't yet written a closure manually.

I later looked up for the definition of closure in js. It turns out a closure is a function in which another function defined within it is returned. e.g.

function myFunc(){
  var name="James";
   function displayName(){
      console.log(name);
   }
   return displayName;
}

or,

function myFunc(){
  var name="James";
   return function displayName(){
      console.log(name);
   }
}

A closure is a special kind of object that combines a function and the environment in which that function was created. You can use a closure where you normally might use an object with a single function.

The main advantage of a closure compared to a normal function is that it is associated with the environment data in which it was defined, and such data is hidden automatically from the outside of the closure. The closure is often used to provide a functionality to other codes, to emulate private methods in o-o programming, or as an object factory.

References: http://howtonode.org/why-use-closure https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures