JavaScript Closures

Paige Miles
2 min readApr 11, 2021

What is a closure?

According to MDN:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

In other words, a closure is a function that has access to an outer function's scope.

What is scope?

Scope refers to the visibility of variables, functions, and objects in a particular piece of code during runtime. Scope can be divided into the global and local scope.

Global scope — variables defined outside a function and can be accessed from anywhere within the program. E.g. name is accessible throughout the program, even inside the greeting function.

let name = “Paige”;function greeting(){
console.log(name);
}

Local scope — variables defined within a function and can only be accessed from within that function. E.g. message variable is accessible within the greeting function only.

function greeting(){
let message = “hello”;
console.log(message);
}

Back to what is a closure?

Now that we know about scope, and we look back at the definition of closure — a function that has access to an outer function's scope — we can see why closure is special.

In the example below, the outer function returns the inner function. The inner function has access to the variable x, even though the outer function is complete and ceases to exist.

function outer() {
let x = 2
return function inner(y) {
return x*y
}
}
let multiplyByTwo = outer();console.log(multiplyByTwo(3));

The inner function is said to close around the outer function's scope.

--

--

Paige Miles

Full-stack developer. Funny-peculiar. Lover of baking, yoga, and reading (between the lines).