Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Why does closure only happen if I assign the return function to a variable?

Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

function counter() {      var _counter = 0;      function increase() { return _counter++ }      return increase; }  // Double ()() to call the returned function always return 0, so no closure.  counter()() // returns 0 counter()() // returns 0 counter()() // returns 0 counter()() // returns 0  var createClosure = counter();  createClosure() // returns 0 createClosure() // returns 1 createClosure() // returns 2 createClosure() // returns 3 
like image 403
sandre89 Avatar asked Nov 17 '17 03:11

sandre89


People also ask

What happens when JavaScript function reaches a return statement?

When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

What creates a closure in JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What are the disadvantages of closures in JavaScript?

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.

Are all functions in JavaScript closures?

@Novellizator (and georg): This may or may not be true for other languages, but in JavaScript, all functions are closures. It's intrinsic to them, in JavaScript. There is nothing special about closures over other contexts that marks them out as distinct from functions that only close over the global context.


1 Answers

_counter is the local variable within function counter(). Every time when you call counter() a new _counter will be created.

But var createClosure = counter() only called the function 1 time, that's why _counter is not newly created every time and 'remembered' there (that's where closure happens)

like image 104
Xin Avatar answered Oct 27 '22 05:10

Xin