DEV Community

Alex Gwartney
Alex Gwartney

Posted on

Explain Javascript Closures

So could someone give some examples as to how closures are useful? As I get its way of not using global variables. and you access it by creating two functions and returning the nested function.

Other than this I really don't see where or why you should use it.

Top comments (5)

Collapse
 
stereobooster profile image
stereobooster

Closure is a technique for implementing lexically scoped name binding in a language with first-class functions.

Without closure code like this (or similar):

function a(x) {
  let y = 0
  function b(y) {
    return x + y
  }
}
Enter fullscreen mode Exit fullscreen mode

would not work as expected. It would either have no access to x or all variables would need to be global.

How closures used:

  • for state - the same way as you can use OOP class to store state
  • for lazy-evaluation - you can "pack" some function with data and postpone it's evaluation till you need it
  • for all tricks with first-class functions, for example memorization (state), debounce (lazy-evaluation) etc.
Collapse
 
tifflabs profile image
tiff

See this is a really complicated explanation. I have had this same question, and this answer doesn't satisfy me at all. I still don't quite grok this. Can you give a simpler answer, like I'm five?

Collapse
 
imthedeveloper profile image
ImTheDeveloper

Agree definitely would love to see real world examples from someone's code where they can justify the usage of the closure and their thinking behind why they decided to go that route.

I see a lot of "good practices" usually when this topic comes up and also "check out some public repos" but definitely helps to be able to talk a real example through πŸ‘

Thread Thread
 
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.

Collapse
 
peerreynders profile image
peerreynders • Edited

Have a look at How to decide between classes v. closures in JavaScript and OOP with Functions in JavaScript.

For some more background see Chapter 7: Using Closures or MDN: Closures.

Then there is always the The venerable master Qc Na with his student Anton:

  • Foolish pupil - objects are merely a poor man's closures.
  • When will you learn? Closures are a poor man's object.