Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Closure Clarification?

As many as Articles as i've read , I still have some questions.

I already know (and understand) the usages of closure like :

  1. The Infamous Loop Problem ( loop of links with alert on each one of them with kept number)

  2. increased counter (keep calling a function -> which alerts increased numbers)

From here :

inner functions referring to local variables of its outer function create closures

From here :

a closure is the local variables for a function - kept alive after the function has returned, or a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

3 Questions please:

Question #1

I was told that all functions in JS create Closures.

WHAT ??? if I create a normal function with private variable it just create a scope. not closure.

I thought that closure work like this:(from here)

  1. Make an outer, "function maker" function.
  2. Declare a local variable inside it.
  3. Declare an inner function inside the outer one.
  4. Use the outer function's variable inside the inner function.
  5. Have the outer function return the inner function
  6. Run the function, and assign its return value to a variable

exmample:

function functionMaker(){
   var x = 1;
   function innerFunction(){
     alert(x);
     x++;
   }
   return innerFunction;
}

So why do they say that every js function create closure ?

Question #2

Does Self-Invoking Functions aka IEFA - Immediately Invoked Function Expression creates a closure ?

looking at

(function (a) {
    alert(a);
})(4);

I don't see the pattern like the 6 rules from the above : where exactly Have the outer function return the inner function is here ? I dont see the word return.

Question #3

function myFunction() {
  var myVar = 1;
  var alertMyVar = function () {
    alert('My variable has the value ' + myVar);
  };
  setTimeout(alertMyVar, 1000 * 3600 * 24);
}
myFunction();

Does myFunction was alive for the whole day here ? or it was ended as soon after the setTimeout ? and if so , how did SetTimeOut remembered that value ?

Please help me to get it right.

like image 689
Royi Namir Avatar asked Nov 21 '12 14:11

Royi Namir


People also ask

What is disadvantage of closure in JavaScript?

Disadvantages of closures There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.

What is closure in JavaScript with real time example?

In JavaScript, closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned.

What is the benefit of closure in JavaScript?

The first benefit of closures is to preserve local variables within the scope. Since JavaScript functions are first-class citizens, developers often encounter name clashing, which will cause some unexpected output. Using a closure can help preserve the namespace in that scope as a private variable.

What could be the alternative to closure in JavaScript?

Top Alternatives to Closure CompilerA bundler for javascript and friends. Packs many modules into a few bundled. Code Splitting allows to load parts for the application on demand. Through "loaders" modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff. ...


1 Answers

All function calls create a closure. The important thing to note is whether the closure lasts beyond the lifetime of the function call.

If I do an immediately-executed function:

var value = (function() {
  return 4;
})();

then a closure is created, but discarded when the function returns. Why? Because there are no surviving references to symbols defined in the closure. But here:

var value = function() {
  var counter = 0;
  return function() {
    return counter++;
  };
}();

the closure lives on after the immediately executed function, because it returns another function that, in turn, includes references to the "counter" symbol defined in the original function. Because that returned function is still "alive", the closure has to be retained by the runtime system.

Note that here:

var value = function() {
  return function(a) {
    return "hello " + a;
  };
}();

even though the outer immediately executed function returns a function, that function doesn't reference any symbols from the outer one, so there's no need to preserve the closure.

I guess what I'm trying to say is that it's helpful to think about the closure as part of the effect of executing a function, rather than strictly as a static, structural thing. It's possible to have a function that sometimes creates a persistent closure, but not always.

like image 122
Pointy Avatar answered Sep 17 '22 20:09

Pointy