JS - What are Closures
Owen Boreham
Posted on June 19, 2021
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...
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()
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;
}
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
}
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.
Twitter: @bobrossrtxSocials
YouTube: Owen Boreham
Medium: @bobrossrtx
dev: bobrossrtx
Github: @bobrossrtx
Posted on June 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 17, 2024