JavaScript: Closures

Jonathan Wong
2 min readOct 11, 2020

What is a closure in JavaScript? Let’s first briefly discuss scope to build a foundation. There are two scopes in JavaScript. There is local scope and global scope. Local scope refers to variables declared inside a function only being available within that function. Local scope may also be referred to as function scope since they’re only accessible inside said function. Global scope refers to variables that are assigned outside a function that become available to any function, making it global. Look down below for example.

function localScope() {
const localScopeExample = “This variable can only be accessed inside this function!”
}
const globalScopeExample = “This variable is accessible everywhere!”

Because local variables are only accessible within the function they’re declared in, you can reuse the same name inside another function without causing issues.

So what does this have to do with closures in JavaScript? In short, it is a feature where a function that is nested within a function, has access to variables declared and assigned in the outer function. This is also called lexical scope. The surrounding state is called the lexical environment. That’s a bit confusing so I’ll provide you an example for clarity.

let firstVariable = “It”
function outerExample() {
let secondVariable = “really does”
// the above variable is accessible in the function nested below
function innerExample() {
let thirdVariable = “work”
console.log(`${firstVariable} ${secondVariable} ${thirdVariable}`)
}
innerExample()
}
outerExample()

Try this out in your IDE to see what I mean.

In summation, among other reasons, closures can give privacy or reduce access to certain variables. Think about why one even declares and assigns variables inside a function as opposed to outside the function. Variables created on the global scope are accessible everywhere and can even overwrite variables on your browser window. When you declare a variable inside a function, local variables are deleted after the function is done executing. Global variables are deleted after the page the function is running on, closes. Each closure has its own lexical environment.

Check the link out down below for more information!

--

--