DEV Community

Damien Cosset
Damien Cosset

Posted on

Explaining closures to myself

Introduction

I write because it helps me retain informations. Whatever subject I'm studying I force myself to put it into words, like I'm teaching someone else. My main purpose is not to teach others though, but to teach myself. We always think we understand something, until we have to explain it. Those who know, do, those who teach, do it better. I'll try to teach myself closures in this article.

Closures

The definition of closure is as follow:

A closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Scope

To understand closure, I must first understand scopes. The scope in a program is a set of rules for storing variables in some location and retrieving them later.
Certain structures in a program create their own scopes ( functions, ifs, for loops ...). If I declare a variable inside a scope, it is not accessible in an other one.

// I am in the global scope
const a = 'Damien'

if( true ) {
  // This is a different scope
  const a = 'John'
  console.log(a) //John
}

const func = () => {
  // This is a third scope
  const a = 'Joe'
  console.log(a) // Joe
}

func()
console.log(a) // Damien

Enter fullscreen mode Exit fullscreen mode

If you try to retrieve a variable that do not exist in the current scope, Javascript will look for it in the outer scope. Javascript will repeat this process until there are no more outer scope to inspect. If the variable is not found, you'll get a ReferenceError:

// I am in the global scope

if( true ) {
  // This is a different scope
  const a = 'John'
  console.log(a) //John
}

const func = () => {
  // This is a third scope
  const a = 'Joe'
  console.log(a) // Joe
}

console.log(a) // ReferenceError
func() 
Enter fullscreen mode Exit fullscreen mode

I removed the variable declaration in the global scope. When I try to retrieve it, Javascript can't find it and returns an error.

// I am in the global scope
const a = 'Damien'

if( true ) {
  // This is a different scope
  console.log(a) //Damien
}

const func = () => {
  // This is a third scope
  const a = 'Joe'
  console.log(a) // Joe
}

console.log(a) // Damien
func() 
Enter fullscreen mode Exit fullscreen mode

In this case, I removed the variable declaration in the if block. Javascript can't find the variable a in this scope, so it looks in the outer scope. The program finds a = 'Damien' in this outer scope ( the global scope ) and uses it.

Back to closure

So now, I understand a bit more about scopes. Closures allow a function to access its scope when that function is executing outside of its scope. Let's see this in action.

function outer(){
  const a = 'Damien'

  function inner(){
    console.log(a)
  }

  return inner
}
const func = outer()

func() // 'Damien'

Enter fullscreen mode Exit fullscreen mode

Why is this a closure? To be a closure, this would mean that the function inner is being executed outside of its lexical scope and still having access to its scope. So what happens here? The function outer returns a reference to the inner function. We execute the outer function and pass it to the func variable. Then we execute the inner function by calling func(). inner is executed, but outside of its declared lexical scope. It's executed outside the outer function. In theory, the program would free up space and see that our outer function is no longer needed ( garbage collector ).

inner has a lexical scope closure over that inner scope of outer. This keeps the scope alive for inner to use. The reference that inner has in the outer scope keeps that scope alive. ==> CLOSURE.

More examples?

Ok, it's still a bit blurry. Could you give me more examples? Perhaps real-world ones?

function chrono( message ){
  setInterval( function timer() {
    console.log( message )
  }, 1000)
}

chrono('GOGOGO')
Enter fullscreen mode Exit fullscreen mode

timer has an reference to the chrono inner scope. That scope is kept alive even after 1 seconds where the chrono is clearly no longer needed by timer. Because that scope is still alive, timer can print 'GOGOGO' every second.

function myModule(){
  const name = 'Damien'
  const age = 25

  function sayMyName(){
    console.log(name)
  }

  function sayMyAge(){
    console.log(age)
  }

  return {
    sayMyAge,
    sayMyName
  }
}

const boom = myModule()

boom.sayMyAge()
boom.sayMyName()
Enter fullscreen mode Exit fullscreen mode

Module Pattern! sayMyAge and sayMyName are both executed outside of their lexical scope. But because both have references to the myModule inner scope, the scope is kept alive for them to use the name and age variable.

Closures ftw!

Top comments (10)

Collapse
 
brianjmiller profile image
Brian J. Miller

Careful with the definition of scoping here. The 'ifs' and 'for' loops do not create a new scope in JavaScript for just any "declared variable" as it has both "function scope" and (now) "block scope". Also, you aren't really "declaring variables", you are declaring constants. "Variables" declared with const or let have block scope, those declared with var have function scope.

Ref: developer.mozilla.org/en-US/docs/W...

Collapse
 
damcosset profile image
Damien Cosset

I see. Thank you for the clarification.

Collapse
 
isramv profile image
Israel M

I am currently reading closures, I recommend the following book github.com/getify/You-Dont-Know-JS...

specially if you want to use parameters in your nested functions.

Thanks for the post.

Collapse
 
tunna29 profile image
tunna29

can you share other link, the link above died

Collapse
 
andre profile image
André König

@tunna29 : I just identified the respective file for you ☺️ The directory has been changed within the repository and the previous link above was pointing to the main branch.

This is the file you are searching for: github.com/getify/You-Dont-Know-JS...

Collapse
 
isramv profile image
Israel M • Edited

I am currently reading about closures, I recommend the following book github.com/getify/You-Dont-Know-JS...

Thanks for the post.

Collapse
 
damcosset profile image
Damien Cosset

Yes! This book ( and the whole series ) is really amazing if you want to understand key concepts in Javascript.

Collapse
 
bengreenberg profile image
Ben Greenberg

Great explanation of a concept that can otherwise be hard to fully understand. I appreciated it.

Collapse
 
damcosset profile image
Damien Cosset

Glad it helped!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.