Javascript Closure tutorial ( Closures Explained )
HTML-код
- Опубликовано: 17 ноя 2015
- 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/js-masterclass/
*couponCode*=TECHSITH-9.99
www.udemy.com/course/react-ho...
Follow me for technology updates
* / techsith
* / techsith
* / techsith1
* / 13677140
* / patelhemil
Help me translate this video.
* ruclips.net/user/timedtext_cs_...
Note: use translate.google.com/ 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!
agreed
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" 😂
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
"Todey we learn about closures", gonna send my ex this for the closure she never gave me.
Lol Bruce Lee..:)
🤣
"Closures are nothing but FUNCTIONS WITH PRESERVED DATA", I'll never forget this. Thanks a lot! Awesome video.
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.
Thanks for the clarity of this. This actually taught me more than I thought I knew about closures.
You are awesome. Now I finally get closure. Thanks
"You can't get simpler than this", you nailed it. Thanks.
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.
Your tutorials are a breath of fresh air! Thanks!!
"Jahapana tu si great ho tofa kabul karo"..................hats of to u sir for explanning these in simplest of terms ever possible.
This was a fantastic video! I've been scratching my head on closures for a while, this brought it all together. Thanks!
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!
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.
anytime I don't understand something i immediately start to looking for you man. your simplicity and way u explain anything is unmatched
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 !!!
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 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 ..
best explanation for closures , you made it look so simple . people often confuse others while explaining . you know how to teach
This so much clearer than I have heard in these bootcamps.
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! :)
2:54 LMAO would love to see the interviewer's reaction
You straight up just blew my mind. I'm crying I'm so grateful!!! 😭 This = Beauty in simplicity
Definitely the best video I've seen on closures thus far. Thanks for sharing your knowledge with us!
Best explanation ever of closures !
Thanks for watching Amelie :)
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 came for the closures explanation, the ASMR tingles just sweetened the deal.
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!
omfg you are amazing! thank you very much i learned something valuable today :)
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.
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. :)
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.
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
I like how you ended interviewing the interviewer. Interviewers can be overbearing sometimes.
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!
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!
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
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.:)
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 :)
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!!!!
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
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 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.
Thank you for explaining this concept in a straightforward, concise way. It made closures easy to understand and implement.
Very nice explanation and you are not very fast too..so easily understood..:) Thanks and regards.
+priyanka tripathi Thanks for watching. :)
You definitely has the looks of a Sith. btw great video
Thank you for simplifying the subject and explaining so clearly! It helps a lot!
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!
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.
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
Finally i get an initial clear understanding about closures. Thank you.
after watching several videos, and going trough this video twice. i finally got it. thanks alot!
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.
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.
Great! A video that just shows how a closure works without bulking the functions with unnecessary content and confusion.
Thanks for watching mate.
Best tutorial so far on closure
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
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
Great explanation! This is the first video where I understood closure, Thanks
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!
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.
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!
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!
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!
For the first time I understood closures. I was searching for a tutorial like this. Thanks a lot :)
Thanks for watching :)
Thank you for such a amazing and simple defination of closure.
Thumbs up! Keep posting such simplified videos!
Best vídeo about closures! Thank you!
This is such a detailed and easy-to-understand explanation. You have my five cents legend!
Thanks, this was much clearer than other explanations I've seen!!
Much wisdom - simply explained
Such an easy and light weighted explanation. Thank you mr. patel.
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 :)
Hey Thanks man, this has been the simplest tutorial for me to understand closures. Thank you very much.
This is excellent, simplest as said "PERFECTLY" 👍
Amazingly explained. Thank you very much, please do keep making such tutorials!
Thank you for bringing so much clarity! This nailed it!
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.
Thanks a lot!
I'm trying to understand closures for days and finally it made sense to me!
Today i got a chance to look at your videos and I love the way you explain the topics...cheers.
this is the best explanation I ever had about this.
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.
natural educator, love techsith, love from UK!
Oh my GOSH! Thank you! That’s so simple and clear!
Glad it was helpful!
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.
simple and clear. easy to understand. thanks.
Okay, im watching all your videos now. These are REALLY great ! You're such a good teacher! Keep it up - Subbed !
Thanks for watching:)
Awww! you have explained all,thanks,I have understood.
best video for Closure, now I have better understanding about closure.
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.
Simple and well explained. Now I got it...
fantastic. clear as daylight!
This is very clear, thank you!
Explained very simply. simpler than this is impossible.
Awesome explanation in most simplest way . !!!!
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
Kickass video on Closure!
Mannnnnnn this video helped me out so much to understand closures. Thank you so much!
You're a star, dude. Never seen it put so simply! You clearly understand this well. :)
Glad you got it. Thanks for watching Georgi !
You real teacher 👨🏫 for me who teaches in simple way thank you sir