What is Javascript's closures ?

If you are a Javascript developer. It's 99.9% likely that you might have used closures, but might not clearly know what was closures.

Let's try to understand it in this article 😉.

What is Javascript's closures ? 🤔

The definition of closures in MDN docs says :

A closure is a 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.

You can see here 😄.

Now, let's try to make it clearly and understand it 💐.

We have index.js file and here code of it is in below.

const myName = 'Ray'

// I used arrow function here. (ES6)
const printName = () => {
   console.log('My name is : ' + myName);
}

printName();

If you're a developer, you probably know the result. Right 😉, the result will be :

My name is Ray

You probably don't realize that code block above is using closures 🤗.

🥳 Let's break code block above down 🥳.

The way closures works in Javascript is that every scope has access to everything outside of its scope. For example : You have a file index.js above, it is one scope. You also have printName function is another scope. You can see myName is an external variable outside printName function. But it's acctually available inside printName function.

One more thing that's really interesting here 🥳. Let's change code block above to code block below.

let myName = 'Ray'

// I used arrow function here. (ES6)
const printName = () => {
   console.log('My name is : ' + myName);
}

myName = 'TaiMD99'

printName();

When you run this code, the result will be

My name is TaiMD99

The printName function is not taking value of myName that is defined when it is defined. It's actually taking the current live value of myName variable.

I hope that this article is useful for you and helps you to clearly understand Javascript's closures and how it works 🥳🥳🥳.

If you have any question about Javascript's closures, comment below.

Thanks for reading 🙏.