Member-only story

JavaScript Closures Explained:

habtesoft
4 min readAug 22, 2024

--

Unlocking the Power of Private Variables and Functions

JavaScript closures are a fundamental yet often misunderstood concept in the language. They play a critical role in creating private variables, managing state, and building powerful abstractions. This article’ll explore closures in-depth, understanding how they work, why they’re useful, and how you can leverage them in your JavaScript code.

Not a Medium member? Read this article here

What is a Closure?

A closure is a function that remembers the environment in which it was created, even after that environment has gone out of scope. In simpler terms, a closure allows a function to access variables from an enclosing (outer) function even after the outer function has finished executing.

How Closures Work

To understand closures, let’s start with a basic example:

function outerFunction() {
let outerVariable = "I'm from the outer function";

function innerFunction() {
console.log(outerVariable);
}

return innerFunction;
}

const myClosure = outerFunction();
myClosure(); // "I'm from the outer function"

Here’s what’s happening:

  1. outerFunction is called: When outerFunction

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

Responses (2)