DEV Community

Discussion on: Explain Javascript Closures

 
stereobooster profile image
stereobooster • Edited

From implementation point of view every function in JS is a closure (probably modern JS engines can do some tricks to "flatten out" them). Based on this to ask why we need closures is like to ask why we need functions. Probably this is not what you meant...

There are functions which could work with closure or without (from implementation point of view), for example

var counter = 0
function increase() {
  return counter++;
}
Enter fullscreen mode Exit fullscreen mode

You can implement this function in C (which doesn't have closures). Other functions can't work without closures, for example

function a(x) {
  return function () {
    return x
  }
}
Enter fullscreen mode Exit fullscreen mode

Function which returns function needs to use closures - it's not a choice. It's like bird uses wings to fly not by choice - it's the only way.

Based on this I guess you asked: what is the use case for functions that return other functions.

Answer: functional programing techniques. Whole idea of functional programing is based on the fact that you can treat function as value.

Examples:

UPD: after I wrote it I realized this is still not a precise explanation. You can return function pointers in C, but those functions can't access outer scope variables... the correct answer would be is that closures needed for "lexically scoped name binding in a language with first-class functions"...

lexically scoped - means that function (in this case) can access all values from outer scope and values from inner scope doesn't "leek" outside. For example, let and const are lexically scoped, but their scope is any block ({, }) not just a functions. Note the difference even though they are lexically scoped, you don't need closures for for loop, because you can't "return" for loop - it is executed once and nothing holds reference to it's inner variables.

first-class functions - functions that can be treated as values, e.g. you can assign function to variable, you can pass function as a param, you can return function from other function.