Closures in JS ๐Ÿ”ฅ | Namaste JavaScript Episode 10

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
closures you know i was super excited about this topic and by the end of this video you will understand everything about closure you will have a good knowledge and you won't have to go to any other video so let's just begin so let's just start with the most basic example of closures for that let me just create a function let's name it x okay and let's have a variable a inside a function and let's call it 7 7 is my date of birth and let's i have our inner function let's create another function inside it let's call it y because it comes after x i don't know okay and let's just do nothing but just log a inside y okay so and what let's do let's call this function y and let's call x also okay so now my dear friends because you have watched the lexical scope previous video right so you already know what will be the output of this right so you know that javascript has something known as lexical scope so when you execute when y tries to run it tries to find this a inside this local memory store and it does not find it so it goes to its lexical parent right and it what does it logs you already know right let's see in the console let's run this program and let's see in the console yes my dear friends let's see it but let me tell you that this is what closure is [Laughter] i know you must be thinking that akshay are you kidding me but no people this is what closure is it is that simple okay we kind of make it like so much complicated but let me show you okay let's dive deep inside the browser and in the console let's just put a debugger right where inside the inner function okay before just before doing a console log i have put a debugger and let me just hold on our program there and see you find this closures over here right what does this mean now okay interesting and weird right it it was it that simple yes it was that simple but you know what does that mean okay so closure basically means that a function bind together with its lexical environment okay let me repeat it once again closure is a function together like bundled with its lexical environment or closure along with its lexical scope together bundled is known as a closure it forms a closure function along with its lexical scope remember this function along with its lexical scope forms a closure that's known as closure okay so let us now also see why it looks something like this so it says that why right we have hold our program onto y right so inside y it forms a closure with the variable which were part of x lexical scope right the function y was bind to the variables of x so that means it forms a closure and it has access to its parents lexical scope okay so that's what it is right so now just let's go to the mdn docs and check what is closures right what it has to say about closures okay so closure it says that function bundled together to its surrounding state or the lexical environment right function along with its lexical environment right it's enclosed it's a closure okay so my friends in simple terms that is what closure is okay but now let's move to a little more complicated examples and you will love this okay so remember i told you in my previous videos functions are like heart of javascript right functions are very beautiful in javascript what you can do with functions is so you know this function you can just grab this and you can even assign functions to a variable okay right this is how beautiful functions is okay you can do this in javascript this is a perfectly valid javascript and not just this you can even grab this function and you can like pass it into function okay so you can literally pass this function inside a function as a parameter right most of the programming many programming languages won't allow this right but this is the beauty of javascript and this is how beautiful functions are in javascript that you can pass them along with it and similarly you can even return these functions from function what yes you can return this function out of this function also how you know instead of just calling it you could have just return it right return this function so it it might be crazy for people who are coming from other languages right so how can you like kind of return this value of function what what is it what does that mean actually okay but you can literally do it let's see okay and that is where closures come into picture and becomes more complicated okay when you return these functions outside right outside okay so first of all what does this mean when you return this y what is y okay so why literally is like the function okay this function itself okay this whole function code is y right so when you return it what it returns actually let's just see okay so what will happen once you invoke this x it returns y okay and it returns this y to the place where functions was invoked right so that means when you execute this y will be returned over here let's grab this into a variable and see what it is okay so um let's call it z okay and let's see what the return value of this function call will be okay so let's just kind of do a console log of z okay let me show you so what do you expect to see my friends can you give a little guess here let me just remove the debugger yes you are right it gives us the function y right so what happened just now okay you call this function x so remember what happens when we call a function invoke a function from the previous videos it creates an whole brand new execution context it sets up the memory space variables this that so many things and it kind of return this value y okay this function y it returns it right it returned it into z and what happened x was like vanished okay javascript is synchronous right so after running this line 8 x is gone right once why his return right so x is now gone x is no longer in the call stack x execution context is no longer in the call stack like it's completely gone all the variables everything is gone right but what will happen to this y now so now our z contains this function y right now here things become more complicated because what you have done is returned a function okay now you already know what happens to this function when it is inside a function right you know all that lexical scope lexical bindings parent and the scope chain and everything right but once this function has been returned outside right now we have returned this function so now it no longer resides inside x right so how will this behave in other lexical scope okay so now this z has a reference like has this function y right inside it so how will this behave outside this scope right before it was inside x right now we can like literally use a z right z outside right outside the scope outside of x okay and the more interesting part is right suppose we have written thousands of line over here suppose suppose there are thousands of line over here okay and at some point of time in our program we just want to call that function okay call that function z what will happen what is there in z z is this code is there in z right so what will happen can you give it a guess it will it will try to find out a but where is a right we are trying to execute z outside a a is not there in the global scope and x is gone right it's not there it's no longer exist after line number eight so what will happen to this a where will it what will happen will what will it print when you invoke z what will it print will it print undefined or will it print null or will it print some other value what does it print it will print let's see see it prints seven okay interesting right so here comes closure into picture okay so functions i said are so beautiful that when they are returned right when they are returned from another function they still maintains their lexical scope okay they remember where they were actually present right so though x no longer exists nothing is there but still this y function remembers its lexical scope where it came from okay so it came from here right so it remembers that there was something known as a and it has the binding strong there okay so if i call it in a simple way when you return this y right so not just that function code was returned but a closure word return okay that closure enclosed function along with its lexical scope that was returned okay so it's not just that function but that whole closure function along with its lexical scope that was returned and it was put inside z so when you execute z somewhere else in your program right it still remembers a so it still remembers the reference to a remember reference to a and it tries to find out value of a which is seven right and it kind of prints it that's what closure is and you know this is the small thing which many even senior developers don't understand okay even a lot of people with a lot of experience don't understand this small thing okay but this is what closure is okay so next time your interviewer asks you what is a closure right so don't answer like function returned a function and this and that and whatnot don't don't just say all that just say function along with its lexical scope bundle together forms a closure that is what closure is okay and you can give this example you know you can better explain this example now right so this is what you have to tell in the interview this is like the most common and the most asked interview question right so this is what this is how you have to answer this okay so now if you're feeling confident that you will be able to answer this question if as in the interview then give this video a like button right now okay before we move on to the complicated thing and by the time you hit that like button let me just show off by drinking my green tea that i drink green tea okay who drinks green tea so now moving back okay so some cool developers right that cool developers instead of writing like this return why okay what they do is they just try to return okay and they just put this return outside over here in front of that function okay so it's it's same it's simply same okay it's like defining a function and then return that y or you can just write return and a function over here so many like new developers like find this complicated okay this this syntax kind of looks like what is it doing like x is like returning function return function why what the what the hell is going on okay it looks like that but it is like exactly same what we wrote okay it behaves the same way nothing nothing complicated i just wanted to highlight this point okay so if you find this kind of syntax don't get like panic when you see this kind of code it's it's nothing right it's it's simple you just return a function it's it's as simple as returning y right you can just assume that you are returning this whole function that's it nothing more okay so you know closures come with a lot of gotchas also here and there just because that function was returned so it comes with a lot of corner cases and this that there are a lot of unanswered question that becomes uh like a lot of output questions okay in the interviews and like people mess up their head so let's cover few more gauchos and corner cases you will be like love this part right so i'll show you few things like small nitty gritty things okay what will happen let's cover them so let me just move on to that previous code yes so we had a function y and it returned y right so some people also gets confused with this so suppose if i did something like this okay before a was 7 right over here a was 7 so what if before returning y i changed a to 100 okay if i changed a 200 right so what will you what do we expect now okay so when it returns okay when it returns y so will now will now this execution of z be hundred or seven what will it be can you guess so it will be hundred okay if i run this code if i run this code c it will be hundred why because c so let me just explain you properly so when you return this y from here right so if you return this y this was this function isn't it so what will happen it comes along with its lexical scope so over here a a does not refer to the value right some people think that it refers to seven over here okay so when y was y was in the memory so a was seven so a might be seven no it is as reference okay is reference which is returned okay the function along with the reference to those variables okay not just the value right the value seven does not persist the reference to a persist okay that stays or the function remembers the reference to that is memory location that label a the identifier a okay whatever you call it as but it is the reference to that variable okay and when it is running z okay it will try to find out the preference a and now that when it is executed now that reference points to 100 isn't it so that means that 100 is still in the memory preserved because of closure and when x was gone it was not garbage collected because it has to be used later okay so that way that closure is like giving us hundred so that is why this hundred is printed right not seven so many people gets confused uh with this concept also so now let me show you another important thing and a gotcha okay so what will happen okay it's it's an interesting part so suppose uh if this whole thing right if this whole thing was inside a function okay let's let's take one more level let's go one more level deep inside the scope chain okay so if suppose i had a function z and that whole code right that whole code was inside it i don't know what happened with my uh formatting oh i i had a plugin here i don't know what is happening so so okay so if i put whole code inside right inside this so what will happen if i was accessing variables of one more parent right one more level parent from the deepest function okay so suppose if i had a variable b is equals to let's say 900 okay i don't know why it came into my head okay and if i use so now see clearly carefully okay so i am trying to access its parent scope also and its parents parent scope also so now will it still be a closure let's see by going deep inside the browser okay let me just save it and let me just go to sources i put a debugger inside the innermost function um it doesn't let me put debugger oh i haven't called it okay okay sorry sorry so let me just call these functions okay if i call my y over here and if i call my x right after declaration and if i call my z also okay now what will happen okay and let me put a debugger right over here okay in this line so now you see interesting thing right so it has a closure over here so that means y forms a closure okay along with like the scope of x and scope of z okay so however you may want to call it as okay but closure is like function along with its scope okay that is what whole closure is so see over here if you see if you see it forms a closure along with this variable b which was its parent's parent okay and along with a which is its parent okay so that is known as closure okay and this is how it works behind the scenes and if i would have like kind of returned this value like return this function y right outside somewhere so it would have retained these um these a b right these memory locations a b would not have been garbage collected okay these would have retained right it would have been retained okay so you know this closure is a very powerful concept of the language and you know just because these functions remembers things right so where even when they are not in that lexical scope right this makes the language very powerful okay and there are a lot of uses of this so let me tell you few common uses of closures okay so in the console let me just paste it out few things which i remember is see closures are used in module design pattern okay there is a design pattern which i will be covering okay we will cover that it is like you will see closures closely inside the module design pattern it was it is not possible without it carrying in javascript i have made a video on carrying right you can go and check it out carrying in javascript is possible just because of closures okay and there are few functions like once okay there is a function okay there is a i don't know if you have used it or not but there is a function once which kind of gives you a function which can only run once so yeah you can make a function only run once if you run it twice it kind of doesn't run okay so this is by how this is possible if you just give a moment to think so when function you know what is a function in javascript so function can be called anytime any any number of times right that is what the functions are meant for but you know this this is possible just because of closures that function remembers right remembers something right so you can like kind of store that how many times the function has been like run inside like by forming a closure and uh that makes it beautiful right so that makes this possible and even in the case of memoize so if you try to use memoize so you will find closures over there you know and if you want to maintain a state in the async world like the like i mean we will do a lot of we will cover a lot of async programming so asynchronous javascript there you will see closers like we will be talking a lot about closures so understand this all properly you might have used set timeouts right so whenever you like kind of do something after some time that is a closure you use a closure okay and iterators and many more there are a lot of uses of closures and closures is like everywhere you know um it's it's like you it's it comes like naturally you know just because you can't see a closure does not mean that closure is not there okay closure is like almost if you are writing javascript for a while you might have used closures but you might not know what was the closure but now with this video i think things would be much better isn't it so just because closures is a very important topic for interviews i will be releasing exclusive videos of closures along with its examples you know there is a very famous question of set timeout in the loops okay which covers a lot of closures and many people can't answer in that interview okay so i'll be covering everything in the next video okay a lot of examples a lot of core and depth concepts of closures how it can be used in practical life and where you kind of make mistakes in the interviews okay i'll be covering all that exclusively so do watch the next video it will be like the bonus video of this video okay these were all how you explain closures in the interviews and that will cover example a lot of example of closures and you will definitely love that set timeout example in the next video before moving on to that video you have to do three things okay three things first is to like this video right now second thing is to share it with your network share it on social media man this this thing is like bugging a lot of developers and the third thing is to tell in comments are you feeling excited or not are you enjoying the course or not what else topics should i cover tell me right here and then okay and till next time thank you for watching namaste javascript [Music] so you
Info
Channel: Akshay Saini
Views: 153,799
Rating: 4.9698834 out of 5
Keywords: Javascript course, Namaste javascript, akshay saini, akshay saini javascript, javascript tutorials, best javascript course, javascript video series, javascript fundamentals, namaste js, javascript core concepts, advanced javascript, closures, closures in js, closures in javascript, function closures, js closure, js closure example, closure function in javascript, javascript closure interview questions, lexical scope javascript, scope and closures, closures youtube
Id: qikxEIxsXco
Channel Id: undefined
Length: 22min 44sec (1364 seconds)
Published: Mon Nov 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.