Several languages have closures, but you will most often hear of them within JavaScript because when defining variables, you don’t always have a good way to handle scope or static properties.
Specifically, it is a form of lexical scoping. This is used to preserve variables from the outer scope of a function in the inner scope of a function. Lexical scoping is the process used to define the scope of a variable by its position in the source code.
This means it is like using a global value, but still within some restrictions, and keeps different libraries and modules from potential interference where global variables may cause problems.
This becomes an issue because using different frameworks and libraries is so common in JavaScript.
Consider the Problem
Consider the following block of code:
let message = "Hello";
function buildGreeting() {
let audience = "World";
console.log(message + " " + audience);
}
message
is in the global space, since it is outside of the function. The issue is anyone can change message, even another library or resource imported into the page. Remember also, if we do not put var
or let
before a new variable, it will be global in nature.
We also have a local scope for audience, where it is only visible inside the buildGreeting()
function.
If I put my global variable inside of another function, it runs into scope issues. Consider the following:
function buildGreeting() {
let message = "Hello";
}
function greetUser() {
let audience = "World";
console.log(message + " " + audience);
}
greetUser();
Building a Closure
To build a closure, we are going to wrap the inner function within an outer function.
function buildGreeting() {
let message = "Hello";
function greetUser() {
console.log(message);
}
return greetUser;
}
// we have to assing the function to a variable for it to be called
let hello = buildGreeting();
hello(); // we can call this and it works
buildGreeting(); // if we call this, we are just returning a function, but not calling it
Closures in JavaScript was originally found on Access 2 Learn
One Comment
Comments are closed.