What is a Closure in JavaScript?JavaScript Basics

Understanding Closures: A Deep Dive into Scopes and Variable Accessibility in JavaScript

Patrick Karsh
2 min readSep 22, 2023

A closure in JavaScript is a concept where an inner function has access to its own variables, the variables of the outer function, and global variables, even after the outer function has finished executing. This means that a closure can remember and access variables from its parent scope (the outer function), even after the parent function has finished executing.

Here’s a breakdown:

  1. Inner Function: The function defined inside another function.
  2. Outer Function: The function that contains the inner function.
  3. Parent Scope: The scope of the outer function, from where the inner function can access variables.
  4. Global Variables: Variables that are defined outside any function and can be accessed from any function in the file.

Example:

function outerFunction(outerVariable) {
let outerLocalVariable = 'I am outside!';

function innerFunction(innerVariable) {
// innerFunction is the closure and has access to all variables listed below.
console.log(innerVariable); // Inner Scope
console.log(outerLocalVariable); // Outer Scope
console.log(outerVariable); // Outer Scope
console.log(globalVariable); // Global Scope
}

return innerFunction;
}

let globalVariable = 'I am Global!';
let closureInstance = outerFunction('I am from Outer!');
closureInstance('I am from Inner!');

In this example:

  • innerFunction is the inner function.
  • outerFunction is the outer function.
  • When calling outerFunction, it returns the innerFunction, preserving the outer scope. Therefore, closureInstance is, in essence, the innerFunction, but it still has access to the variables in the outerFunction scope, even after outerFunction has finished executing.
  • When we call closureInstance('I am from Inner!'), it is equivalent to calling innerFunction with access to the variables from outerFunction and the global scope.

Output of the Example:

I am from Inner!
I am outside!
I am from Outer!
I am Global!

Explanation

Think of closures like backpacks. Imagine the outer function is going to a camp, and the inner function is what it brings back. The inner function brings a backpack (closure) with it, filled with all the skills (variables) it learned at the camp (outer function), and it can use those skills (variables) whenever it wants, even after the camp (outer function) is over. So, the backpack (closure) allows the inner function to remember and use the skills (variables) from the camp (outer function) anywhere it goes!

--

--

Patrick Karsh
Patrick Karsh

Written by Patrick Karsh

NYC-based Ruby on Rails and Javascript Engineer leveraging AI to explore Engineering. https://linktr.ee/patrickkarsh

No responses yet