DEV Community

Owen Boreham
Owen Boreham

Posted on

JS - What are Closures

About me:

Hi there, my name is Owen Boreham, and most people call me by my username... "Bobrossrtx". At the time of posting this, I am a 15 year old teenager hoping to be a get into college for Computer Science. Anyway that is enough about me, lets talk about closures...

summary

I will talk about what closures are and when they are used in this article. All credit of this knowledge comes from Fireship and you can check out his website here.

Closures

Closures are JavaScript functions access variables from the global scope, for example...

// Lexical environment
let myVar = "Hello World";

// Function
function hello() {
  console.log(myVar); // Captures the myVar variable
}

hello()
Enter fullscreen mode Exit fullscreen mode

In order to call a function in your code, the JS interpreter needs to know about the function itself and any other data from the surrounding environment that it depends on.

Take for example a pure function that only depends on it's own arguments.

// No external data
function pureFunc(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

What we have here is a fully self contained closed expression. When it is called, it gets pushed onto the call stack where it will be executed and its internal data (arguments) will be kept in memory until it is popped back off the call stack.

But what if that function references data from outside of it's own scope like from the global environment or an outer function.

// Parent scope
let b = 3; // free variable

// This is a Closure
function impureFunc(a) {
  // Function scope
  return a + b; // Captures `b` variable
}
Enter fullscreen mode Exit fullscreen mode

This leaves us with an open expression that references other free variables from the environment. In order for the interpreter to call this function and also know the value of these free variables it creates a closure to store in the Heap, this is a place in memory that can be later accessed. Unlike the call stack where the it is short lived, the Heap can keep data indefinitely then decide to remove that data when it is no longer needed by using a garbage collector.

So a closure is not just a function, it is a function combined with the outer state or lexical environment. Closures do require more memory and processing power than a pure function but you will come over many practical reasons why to use them.

Socials

Twitter: @bobrossrtx
YouTube: Owen Boreham
Medium: @bobrossrtx
dev: bobrossrtx
Github: @bobrossrtx


Top comments (0)