Why not return function code not working?

Good day!

Can't understand why for the code below the required return to function(). In fact, the value is returned from the inner function, why return the function itself?

function makeCounter() {

 var currentCount = 1;

 return function() {
 return currentCount++;
};
}

var counter = makeCounter();


I understand that the question is banal, but the spear is broken. Thank you. :)
July 2nd 19 at 13:28
3 answers
July 2nd 19 at 13:30
Solution
In this case, you get a kind of factory counters. Each call to makeCounter() returns the object reference functions, and not on its result. Also in this example uses a circuit that gives a return of the function able to refer to the variable currentCount, which has the parent scope.
function makeCounter() {

 var currentCount = 1;

 return function() {
 return currentCount++;
};
}

var counter = makeCounter();
var counter1 = makeCounter();

console.log(counter()); //1
console.log(counter()); //2
// counters are independent from each other
console.log(counter1()) //1


This example is of course more synthetic, but it covers some extremely important concepts in JS, namely: closures, scope, first-class function. First-class function, in turn, means a set of principles followed by all the functions created in JS:
  • Each function is an object or instance objectnova type (instance of Object type)
  • The function can have properties. For example the entry makeCounter.foo = "bar", is absolutely valid. A similar approach is used to create static properties of the function
  • A reference to a function object can be stored in a variable and then call the function. As in your example,counter()
  • You can pass a function as parameter to another function
  • Function can return another function, as in your example


Thus, although this feature does not carry complex logic, but it illustrates many important concepts, without which knowledge will be very hard to understand how a library
July 2nd 19 at 13:32
This code is meaningless, it is the illiterate compiled a training manual or code generated automatically, in practice, the circuit is used primarily when you want to implement not just a function call and the event, in particular for async to understand this and much more - practice with real-world code, such as different API libraries, but does not suffer x....
July 2nd 19 at 13:34
this function creates a counter, this counter is increased, it is necessary to call
var counter = makeCounter();
var counter2 = makeCounter();
counter2(); // 1
counter2(); // 2
counter(); // 1

Find more questions by tags JavaScriptClosure