Javascript Closure tutorial ( Closures Explained )
ฝัง
- เผยแพร่เมื่อ 11 ม.ค. 2025
- What are closures in javaScript and how and where to use them.
So what is closure in javascript?
"whenever you declare a function inside another function, the inside function(s) is/are recreated again each time the outside function is called"
"Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created."
#JavaScript #closures #lexicalScope
*My Udemy Courses
www.udemy.com/...
*couponCode*=TECHSITH-9.99
www.udemy.com/...
Follow me for technology updates
/ techsith
/ techsith
/ techsith1
/ 13677140
/ patelhemil
Help me translate this video.
www.youtube.co...
Note: use translate.goog... to translate this video to your language. Let me know once you do that so i can give you credit. Thank you in advance.
"Closures are nothing but FUNCTIONS WITH PRESERVED DATA", I'll never forget this. Thanks!
Knomo Seikei agreedd. Love how he explained in simple way.
Lovely expression! Thanks a lot
If I use let then we have to console inside the function then it will work but not outside??
"this" 😂
I love this guy too, awesome videos! but maybe he should considerate doing a new video about closures because in newer versions of Chrome we don't have "function scope" or even a "Closure" property for the first example (4:40)
EDIT: to be precise, we do have the Closure property within Scopes, but that only happens in JSFiddle (if you create a simple html page with an embbebed script, there's no closure, does anyone know why is that? because that goes against what the video claims: "any function that access variables outside of its scope is a closure")
It is much simpler, and very easy to understand. I've realized that people are confused about closures because they want to understand HOW CLOSURES WORK by applying NORMAL function BEHAVIOR MODEL (Many tutorials does not help with their explanations and examples, so its not that you are not smart ). But closures does not work like normal functions. Why not learn how do they work instead? We've all learned NORMAL function behavior, that is when you executing normal function, all variables inside are first initialized, used, then when function has finished its execution VARIABLES are DESTROYED. So that is normal function behavior.Simple,right? We all know that, but - Closures does not work like that. So what is closure then? When you have function inside a function it is AUTOMATICALLY a CLOSURE. What is the property of the closures?There is only one that you need to take home and understand! Again, in NORMAL FUNCTION BEHAVIOR: After function has finished its execution, variables are destroyed. Instead, When you have FUNCTION inside a FUNCTION, we now know it is automatically a CLOSURE. CLOSURE has this PROPERTY: When Your engine sees function inside a function, it WILL NOT DESTROY data, data will remain in memory. Imagine like your engine thinks oh wait, i have function inside a function, so this nice dude wants me NOT TO DESTROY variables. So we can access them even after function has finished execution. What is use of that property? Consider following EXAMPLE: imagine you have function inside function ( closure ). You have OUTER FUNCTION with COUNTER set to 0. Then in inner function, because we can access outer function variables we want to do the following: Clicking on a button we will increment counter. What would happen without closure properties, i.e. if they would behave like normal function? Without closure behavior, when we click on a button, it will increment counter to 1 and it will remain 1 no matter how many times we click button. Why? Because, counter value is lost, it is lost because this will be WORKFLOW: 1. OUTER FUNCTION sets counter to 0. 2. Inner function increments counter so now counter is 1. 3. We come to the end of the outer function, so basically we finished with executing a function, so in that regard variables are destroyed in our case counter = 1 is destroyed. Then we click again, it will repeat process, so set to 0, then inner increments to 1, again we come to the end of the function, puf counter is again destroyed from memory. so that is why we always see 1. Then remember, this would be normal behavior without closures. But when engine see function inside function it is automatically a closure, and again to carve in your brains, variables would not be destroyed after function has finished its execution. So counter set to 1 will not be destroyed it will be stored in memory even after outer function has finished its execution. SO REAL WORKFLOW with CLOSURES is this: 1. OUTER FUNCTION sets variable counter to "0". 2. Inner function access that variable and increments it so in memory is COUNTER = 1. 3. Function has finished its execution, BUT being a closure variable is still in memory so not destroyed. Now we have in memory COUNTER =1, now upon clicking the button second time, button engine will know it is closure and will use existing variable in memory ( counter = 1 ), so next time will increment to COUNTER=2, 3, ..NOTE ALSO, all callback functions are automatically closures as well!
Mazdy Soraya Thnx for the example. I am following a javascript tutorial but couldnt think of a practical use of closure. This makes sense. Reminds me of a static variable in java.
Omg would it hurt to paragraph your words 🙄
Awesome further explanation, thanks bud
fuck, thank you so much. FINALLY got it.
thanks man
Hey, you're great. You know how to talk to people at the human level and reach them. And I love the graphics and everything else which assists in the overall visual representation. Just wanted to let you know, you are really offering value to the world with your videos and I appreciate it. Thanks. : )
Thanks for watching :)
Agreed. Your big graphic arrows that point help a lot.
"Closures are nothing but FUNCTIONS WITH PRESERVED DATA", I'll never forget this. Thanks a lot! Awesome video.
A closure is an inner function that has access to the outer function's variables. Obviously the inner function has access to its own function scope ('local' variables defined between its braces), and it has access to the outer function's variables, which are Closures, and it has access to the global variables.
Geez, this whole time I understood the concept but didn't think this is what it was called. It would have been easier to just say it the way you did.
Same here. I feel like I learned this naturally by observing the behavior of the functions I create. I just simply did not know the name of the concept.
@@pbenjay2560 same here
then why does the console say the closure is the outside variable? the console is basically saying the opposite of what you said.
@@michaelrooze278 Console is being called on the function, the fact that is showing the outer variable shows that it has been added to the function in memory, when ever you use a global variable or a variable from out side a function it gets stored as a property of the function in memory, The reason people are so confused is that, its a method we all use all of the time, it didn't need to be given a name as its a fundamental action of the scope chain.
You are awesome. Now I finally get closure. Thanks
put intended
"Todey we learn about closures", gonna send my ex this for the closure she never gave me.
Lol Bruce Lee..:)
🤣
4 Years later and this video is still valid and the best on YT to learn closures. Thanks @techsith!
Some topics are evergreen , closures is one of that, it will always puzzle people forever. :)
Thanks for the clarity of this. This actually taught me more than I thought I knew about closures.
anytime I don't understand something i immediately start to looking for you man. your simplicity and way u explain anything is unmatched
great video. I cracked the job interview because of this video, I was like: I don't know why people make a big deal about closure, it is just a function which has knowledge about its environment yada yada yada.
"Jahapana tu si great ho tofa kabul karo"..................hats of to u sir for explanning these in simplest of terms ever possible.
Your tutorials are a breath of fresh air! Thanks!!
I have been self-learning python and javascript for a couple of years and come across a host of online tutors on the subjects. Undoubtedly, this is the best tutor I have ever seen. His methodology is practical, to-the-point, simple and meaningful! He even has a great personality - - - he genuinely shares his knowledge and skills. Some tutors like to use complicated demos and rather make the coding boring . . . they sound like some of the German idealistic philosophers in the 18th century. If you guys have a plan to consume online coding classes, do not waste your time . . .just go jump and comfortably land yourself on his lectures.
You are blessed with the ability to teach. Keep em coming. Simply awesome. Thanks.
One thing that I would like to know as beginner in JavaScript. Whats the use of preserving data in such a way ..
Great! A video that just shows how a closure works without bulking the functions with unnecessary content and confusion.
Thanks for watching mate.
To sum up my question:
Why is the first time addTo is called, the argument goes into the variable 'passed' but the second time the argument goes into 'inner'?
var addThree = new addTo(3); //3 is assigned to the variable 'passed' here
console.log(addThree(1)); //1 is assigned to the variable 'inner' here.
I am confused by this too! Why is that?
Because when typing:
var addThree = new addTo(3) and var addThree = new addTo(4)
you're creating 2 new variables which have different passed values of 3 and 4 respectively. These don't change when you define them, but can be used interchangeably with the addTo variable and its corresponding function.
When you console.log e.g console.log(addThree(1)); you've already assigned addThree with the passed value of 3. The function then continues to the function within it (the inner function)
This asks to return passed (which you've assigned 3) + inner (which you've called 1) = 4
Let me see if I can help. Well when you call addTo(x) the return value is the add FUNCTION. so addTo(x) is a basically just another function that takes one parameter (inner). You can actually pass "Inner" directly like this: addTo(10)(5); that will return 15 because [addTo(10)] is a FUNCTION expecting the parameter of "inner" which you pass as the second number (5). In fact you can keep going and going inside the "add" function, you can create another function. Here's a fiddle showing an example jsfiddle.net/davidtheprogrammer/d4dvohhv/
Thanks guys, I think I've got it now. Wow, it's almost spooky how the value of 'passed' is preserved in there!
Amazing.. This is brilliant. "addTo(10)(5)" this piece of code cleared all the millions of doubt i had and i would continue to have. Thanks
best explanation for closures , you made it look so simple . people often confuse others while explaining . you know how to teach
I've searched for explanations of closure and this was the first one I found that did an especially good job. Especially the second example. Thank you!
Man, you're a true SITH JS warrior! This is the 5th video I watch on Closures and I FINALLY GOT IT! Liking and subscribing right now.... thanks a lot!
Welcome aboard Kevin! Thanks for watching! Keep on learning!
Watched the video, did not understand the anything. Went through the comment section, got more confused. Went to the toilet and suddenly everything started to make sense. And now I am thankful to everyone. The video is GREAT and everyone in this comment section is also very generous. Thanks everyone. Faith on humanity restored.
I am glad somehow you manage to understand this. :) Taking a break is so important! :)
"You can't get simpler than this", you nailed it. Thanks.
Very well explained.....almost every tutorial explains closure with the example of a nested function...You did the trick by avoiding it at the start
Thanks :)
I'm seriously one of this guys fans. Thanks man I really need to dedicate a week to watch most of your videos. They are gold.
Nice tutorial! This helped me see closures in a different light. I loved the simple examples -- no need to make it more complicated than it already is.
Seriously, I have watched countless tutorials on this subject and it frustrated me so much that no one could explain closures as simple as this guy did. Finally it clicks thanks to this tutorial. CLOSURES ARE FUNCTIONS WITH PRESERVED DATA!!! Why don't any other instructors keep it as simple as that?!?! Thanks for this tutorial. Huge help!
I am gald that you got it. Thanks for watching :)
Thanks for giving me some closure on closures! Haha had to make a pun of it.
I am glad that you got some closure. No more loose ends.:)
I don't usually comment on videos but I just want to say ONE THING - YOU. And your VIDEOS, sir-- helped me land my first frontend role. I am forever grateful!
Thanks for great explanation! One follow up question:
So what is the advantage of using Closure as opposed to using a function with two parameters, like "add(inner, passed)"?
Thanks
This was a fantastic video! I've been scratching my head on closures for a while, this brought it all together. Thanks!
2:54 LMAO would love to see the interviewer's reaction
Hey Mr. Patel! Its been so many years that you uploaded this...and it is still helpin people out...and the link even works...Thanks a lot!
Piyush, glad it helped after all these years. Keep on learning!
Best explanation ever of closures !
Thanks for watching Amelie :)
You straight up just blew my mind. I'm crying I'm so grateful!!! 😭 This = Beauty in simplicity
I like how you ended interviewing the interviewer. Interviewers can be overbearing sometimes.
best explanation for closures i have seen so far. I think the best way to help people understand what closures are is by elaborating what problem closures solve.
Somehow I feel he skipped an important concept here. The concept of closure is that consider you have an outer function(A) with a variable(x) and an inner function(B) using that variable(x). The outer function returns the inner function(return B;). Now consider you make a completely independent variable(say a) and assign the variable the return of the function(var a = A()). Note that what a has is the function B and the function A is DONE. Now you go on and execute a bunch of other lines and then when you do call a(), it executes the function B and still uses the variable x of the function A even after a has been done with, THIS is called closure. The most important concept of closure is the non-volatility of the outer variable even after the outer function has been done with. developer.mozilla.org/en/docs/Web/JavaScript/Closures -> this is better.
In your example, when you assign A() for var a, you are "saving" the state of A() in var a. Therefore, you can use function A in as many ways as you want.
Just want to commend you for brilliant, well structured tutorials, the format you use is approachable and you have a knack for breaking complex scenarios into digestible chunks of understandable information. A true talent, thank you!
Thank you for watching!
I've a different opinion on your fist half of the video.
-Not all the function are Closure.
The Chrome dev.console displays "Closure" as you run the script from "jsfiddle"
Run the same script inside an the dev.console or from inside a html, then the dev tool will not display "passed" inside "function closure"
+Dinesh A correct. I tried with cheome dev console and it just shows
1) with block:cmd line api
2) global:window
+ techsith please answer, as in that case the var passed can't be called as a case of closure
Good observation Dinesh.
As per my understanding , it internally runs the program as shown below.
It is wrapped inside one more function which gets called on window.onload.
window.onload = function(){
var passed = 3;
var addTo = function(){
var inner = 2;
return passed + inner;
};
console.dir(addTo);
}
thank god you mentioned it....the first example here is just lexical scope in order to have closure a function needs to be executed outside of its lexical scope.....so the definition is when a function remembers its lexical scope even if its executed outside of its lexical scope......i learnt this from kyle simpson
Wow I've wasted so much time watching JS OOP lections and reading books resulting in hitting my head and your videos made it all click together, thank you very much!
Very nice explanation and you are not very fast too..so easily understood..:) Thanks and regards.
+priyanka tripathi Thanks for watching. :)
For the first time I understood closures. I was searching for a tutorial like this. Thanks a lot :)
Thanks for watching :)
Why do you use new at 9:20 ? It doesn't seem necessary
It's not strictly necessary. Edit: what I've just written but prettier in jsfiddle: jsfiddle.net/huwt1ah6/1/
/**
* Easy function closure
**/
function addTo(passed) {
function add(inner) {
return passed + inner;
}
return add;
}
var add7 = addTo(7); //
He is explicitly declaring a new function, but as long as i know, JavaScript do this implicitly if you just overlap the new keyword.
Totally agree - things were going well until he brought in that misdirection!
Icaro Rego Fernandes no, javascript doesn't add new keyword implicitly, its function calling in constructor mode,
Which adds special properties to the function and changes the reference of this argument to an empty object
thanks for sharing I didnt complete understand the vid but i get passed it util i look up your code thanks a lot
after watching several videos, and going trough this video twice. i finally got it. thanks alot!
Closures are made anytime we create a function in JavaScript .
They encapsulate their own data while still have access to their lexical scope.
good one
Never fully understood closures before this. Playing around with this in the JS console mad me understand how redux works with its subscriptions. Thank you for this.
omfg you are amazing! thank you very much i learned something valuable today :)
I came for the closures explanation, the ASMR tingles just sweetened the deal.
You definitely has the looks of a Sith. btw great video
Tyrone Oldham
Hey loved the video. Loved the conclusion. A closure is “a function with preserved data” something straight, simple, and sweet. But I am more of a deductive learner instead of inductive. Deductive learning start with a good definition then presents examples and explanations. Inductive learning first begins with explaining and some examples then concludes with a definition.
I wish that more developers would follow the deductive approach (if possible) when sharing difficult topics. Define first then explain, instead of explaining then defining. In many cases the deductive approach will be more straight forward and often shorter. If a definition cannot be explained in a simple sentence, then maybe that definition is attempting to defining more than one thing.
Thanks for sharing. Loved the video. Better than most dealing with closures. Most videos begin with some confusing examples instead of a solid definition. These are the videos that may benefit from using a deductive approach.
Why do you use the keyword 'new'? I just removed the 'new' in jsfiddle, and it ran the same. What functionality does 'new' add here?
+Eric Broberg New actually creates a new object . so if you area planning to create more objects you should use new. if you dont use new, in this case it would work, addTo(3) actually returns a function , so you are essentially copying the reference of that function in addThree rather than creating a new distinct object.
+techsith Please add a tutorial explaining the use of 'new', How at different places 'new' and without 'new' can produce different results
I really appreciate the help. This is the only video I have watched that has provided me with a complete basic understanding from a beginner's perspective. Thank-you!
At 0:13 An instructor, who knows to how to talk to people at the human level, expressing frustration just like us when it comes to other tutorials explaining things in a hard way XD
Thanks, really awesome example! Love the way you word it "Closure are nothing but Functions with Preserved Data"!!!
thanks for watching! :)
for your first example I do not see a closure inside my function scope when I run it through chrome console. Any thoughts?
i only see the global
This is because it should be in outer function. Try something like this in console:
function outer() {
var val = 10;
var fun = function() {
var inner = 212;
return inner + val;
}
return fun;
}
And run below line:
console.dir(outside());
Now, in console you should see "fun" object which is actually a closure. I guess, this is what JSFiddle does - wraps your code in outer function.
thanks! I was having same confusion....
That means ultimately we have to use function inside function. Right?
It means first example is not a closure unless you using a jsfiddle. I think jsfiddle wraps the code into a function, so you have function inside function and hence the closure since inside function accessing parents data. Chrome console doesn't do that, which is right. In essence we should not be calling first example as closure at all. Better to refer MDN site for this.
so lucky to find this channel....feels like I'm in a classroom together with a person who really wishes to teach another person...you sir are a great person :)
When I create my own HTML page it doesn't say closure in Chrome. But when I use JSFiddle it does. Same function as above. What's going on?
Jsfiddle itself is a wrapper so you might see slightly different results.
Right.
When I was learning ES6 I found term Closure it was really not clear, just assumed function's function, but this is really good and got rid my scariness with Closure. Thank you very much sir.
I am glad that video helped :)
the new word are used with constructors, it just distracts my attention here
"Closures are functions which use variables outside of the function", I don't know if i can sum it up this way
yep, that is a very good way to say what closures are.
Definitely the best video I've seen on closures thus far. Thanks for sharing your knowledge with us!
Best tutorial so far on closure
I first learned about closure within Haskell and Prolog context, but have long forgotten about it. Thank you for this amazing video. What a great refresher!
This is such a detailed and easy-to-understand explanation. You have my five cents legend!
I love the energy at the beginning of the video and couldn't agree more. Why do these "Teachers" use complicated examples at the start? Simple explanation first, then transition to complicated. It's that simple. Thank you for the help!
Thanks for making all of these tutorials. You are my javascript Hero. Your explanations are great, simple and straight to the point. I now know how to apply closures in a real live application
+Simon Kalu Thanks you! Really appreciate the comments
You're a star, dude. Never seen it put so simply! You clearly understand this well. :)
Glad you got it. Thanks for watching Georgi !
Finally i get an initial clear understanding about closures. Thank you.
Three years after publication this is still the best and simplest explanation of closures on the internet.
Thanks, I did make another update to this video . Please check it out.
A closure to closure. Great explanation. A function preserves and carries its environmental variables for reuse.
Functions remember any variables that are used within the functions definition, including those that were available to the function when it was DECLARED within its LEXICAL SCOPE.
JavaScript doesn't use DYNAMIC SCOPE at all (in fact very few languages do, Lisp is the only one that springs to mind), so you can basically ignore the word LEXICAL from the above statement.
great job not using jquery or ajax to teach closures on JAVASCRIPT. idk why people try to explain closures in javascript using jquery or ajax and not just simple javascript like you did here. this was a good find thank you
Man you´re my fucking hero. Really, i saw 1000 tutorials but i wasn't getting the answer until i see this. Thank you so much!!!!
Your best line that hits home is when you said that you "look in the current scope and then layer by layer look in the next outer, then more outer, then more outer until you find that variable."
Thumbs up! Keep posting such simplified videos!
Thank you... and please dnt stop explaining and teaching us.
You make learning such a fun ,my best place to sneak in when i am preparing for interviews or when i have a doubt,Thanks your videos are such a saviour !
Thank you for an awesome comment Puja. good luck with your interviews.
Great explanation! This is the first video where I understood closure, Thanks
Great explanation, thank you.
I was initially confused why addThree or addFour’s parameter is the inner. Then i realized when these variables were assigned, they hold the “add” function returned by the “addTo” function.
Hope this helps if anyone else was confused
Hey Carson, I still didn't get this exact part about addThree & addFour. Could you please explain it further?
Ratan Khalsa addThree and addFour is a function (the inner function) returned by calling addTo(3) and addTo(4) respectively. So when you call addThree() or addFour(), you are calling the inner function in addTo(), with the closure 3 (for addThree) and closure 4 (for addFour).
excellent explanation. Thank you for your simple and practical approach.
Great way of explaining what is closure. Still we struggle to explain what is closure and what scenario which used closure in our project. Thanks a ton.
Such an easy and light weighted explanation. Thank you mr. patel.
2020, still the best explanation for closures.
I appreciate the comment!
Hi! I'm quite a complicated guy, so your complicated explanation was actually quite revealing because you went in depth and gave good examples.Thank you Sith.
+Alexandre de Joncaire Narten :) I am glad it helped.
Thank you TechSith , I used to watch many of your tutorial videos to get clear understanding of the main concepts of JavaScript.
Thanks for watching Lobsang! :)
Awww! you have explained all,thanks,I have understood.
Fantastic explanation. Never understood closure correctly but now I do
I am glad that it worked for you . thanks for watching!
Best explanation of Closures i ve seen so far congrats.
Glad you think so!
You real teacher 👨🏫 for me who teaches in simple way thank you sir
Explained very simply. simpler than this is impossible.
Very nice and simple explanation of closures, not only what it is, but even more importantly why you want to use it. You also threw in the bonus of creating objects using function constructors.
This is simple and crisp, I love the way you have explained this, appreciate the lucidness with which you have explained it.
Thanks a lot !!!
The best example of closures on the internet!, Thanks thanks thanks alot
Thanks for watching! :)
Cramming for a technical interview tomorrow and always get stumped on the "explain closures" question. This video will help a lot. Thanks.
Good luck with your interview!
this is the best explanation I ever had about this.
This is the best explanation of closure out there!
Thank you for watching Arjun!
best video for Closure, now I have better understanding about closure.
This is excellent, simplest as said "PERFECTLY" 👍
You might say that you're a sith, but there's nothing dark or insidious about your videos, have a subscribe mate, you've deserved it.
Clear explanation and thanks for also confirming with dir() that what you say is not just your way of looking at it... seeing is believing 🙂
Miriam, thanks for watching and a nice comment. Keep on learning! :)
Today i got a chance to look at your videos and I love the way you explain the topics...cheers.
Clearly explained on Closure. Easy to understand. Learning new things are enjoyable. Improving our confidence level.