What is a javascript Closures?
A closure is a JavaScript feature that allows a function to remember and access its outer (enclosing) function’s variables, even after that outer function has finished executing. In simpler terms, a closure “closes over” the variables from its parent function, preserving them for future use.
Let’s understand javascripts closures with an example
Imagine you have a diary with a lock:
In this analogy:
• The diary is like a JavaScript function.
• The lock is like a closure.
• Your thoughts and secrets written inside the diary are like variables inside the function.
Here’s how it works:
1. You create a diary javascripts (function):
function createDiary(){
let diaryContent = " " ; //This is where you'll write your secrets.
function writeSecret(secret){
diaryContent += secret + "\n" ; //Add the secret to the diary.
}
function readDiary(){
return diaryContent ; //Read the secrets from the diary
}
return {
write : writeSecret ,
read : readDiary ,
}
}
}
2. You get a diary with a lock (closures)
const myDiary = createDiary()
Now , myDiary is like your locked diary
3.You write secrets into your diary
myDiary.write("I like ice cream.");
myDiary.write("I have a pet turtle.");
4. You can read your secrets :
const secrets = myDiary.read() ;
console.log(secrets) ;
you can still access your secrets even though you’ve finished creating the diary.
This is essentially how closures work in JavaScript. The createDiary function creates a closed environment where diaryContent is like a hidden secret. The writeSecret and readDiary’ functions have access to this secret even after ‘createDiary has finished running. It’s as if they “remember” the diary Content variable, just like a closure remembers variables from its parent function.