JavaScript the Hard Parts: Closure, Scope & Execution Context

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to this video on closures closures is one of the most complex and sophisticated aspects of the JavaScript language it rests on a deep understanding of lexical scope of our persistent lexical scope reference of exactly what it means to return a function definition from another function we get those principles down in this video and we have a strong intuitive understanding of closure what does closure let us do closure lets us build functions that remember their previous execution they get a persistent cache a persistent memory alongside we're going to discover that lets us build functions like once and memorise very very powerful tools in our JavaScript toolkit so I welcome you to this video and I look forward to seeing the things we're going to build using closure so in our previous session we saw the power of passing functions in two other functions to make them reusable today we're going to see what happens if we give half functions memories if we allow functions to somehow between their executions which many institutions remember their previous state their previous data from past Runnings that's going to give us superpowers in writing a code it's know how to create functions that I like once it's going to say you can only run me once so so it's a 1 to 5 version and multiplied by 2 you can only run me once and after that if you run me again return out sorry you currently ammonium ami wants or something like that if we have that functions have memories they have some way of remembering the previous time around we can do all sorts of very interesting things normally know when our functions get cooled we create a lie store of data inside of them sometimes known as variable environment local memory we state the data the state of the other function for that functions execution context and only for the life of that functions execution context that means while it's running before it finished executing when that function finishes executing everything gets deleted except what what doesn't get deleted through turned out the return value exactly the other local memory of the function is deleted but as I say what if a function could remember the previous times that it was run what if somehow some of its data could be held on to and not deleted that would give us these supercharged functions that have memories right now functions start from scratch them to me run when you run them you run it finish it start some scratch run again now they can get memories this would allow a function definitions have an Associated cache persistent memory but it all starts with us returning a function from a function that underlying understanding that can be very confusing we get this town this profound concept of closure becomes much more readily understandable so functions can be returned from functions in JavaScript we saw that at the end of our higher-order functions session where we notice that passing in a function or returning out a function was possible in JavaScript because functions are just objects we know we can pass objects around so no problem well let's see this precisely line by line so we have here a function instruction generator which we're then going to cool and store its return value whatever it's returned out of it into generated func let's start the top here Luis kicker's off what are we doing we're declaring a function the destruction generator storing a global memory beautiful there it is XO meetin next line we are declaring a variable called generated fog there it is excellent and what is going to be stored in it median the return value of invoking instruction generator fantastic that's very good now for them can you do as well what do we do when we execute instruction generator what happens we declare a function x 2 before we dump number to the function what we create a new execution you did very well as well very nice there it is a new execution context which represents or ease the space the context the space in which to execute the code of the instruction generator function this code here we didn't write it out here but it's in there we're going to run through that code line by line and store anything that gets declared the local memory just inside this function and by the way when we finish running instruction generator when we return out all this stuff gets thrown away it's delete it gets removed what so everything right here we go what is now Phillip you're right what's the first thing we do inside of this function we declare a function x - x - yeah storybook yeah and it's sort of local memory not in global memory no rights noble Americans we're declaring it inside of instruction generator now median do we execute that x to function at this point no what do we do instead we go to the next I know we asked you to you there no no we're definitely not we are taking the entire function definition and we are returning it out we are returning it out not with his name just the function definition we're returning that function definition out and it looks a lot like this return function no name what has what is it Nam yep and then return num by 2 this whole function definition this whole function definition this whole function definition is all getting returned out into what global variable Z into generated from in place order happens to be variable but it's a placeholder where this function is now stored okay this function which we returned out the functionality formally knows more forward to he grabbed it all and it's now stored as the out isn't the output generated for J is narrator and we sorted in generated funk so Philip what is generated funk at this point it's really x - it's a functionality we used to call x - inside of instruction generator before we returned out that function definition that functionality that set of instructions returned it out and gave it a new global label because inside it was known as about by - but that line will of turned x 2 says JavaScript code look at what x - its own it's this function definition return that out there it is return it out but we don't return out its label we return out just its definition so we've got 2 and the calling of instruction generator returns out the functionality known as x - but it doesn't get a label with it so it gets a new global label generated funk so now Louis how could I out here this is a functionality formerly known as x - no it's now out here how could I refer to the functionality that was inside known as what why - how do I call that function out here in global execution context generated I could run generated funk by adding parentheses obably want to pass in something right which would be probably a good - they say three because generated funk is the functionality we defined inside of instruction generator cool water father - between then returned out into the global variable generated funk there it is yes it happened to be like a variable but it can be whatever can be stored under this label here and instantly generated funk can now behave as a function alright let's keep track our execution contexts that means the coolest of functions we started off in global and then we started running instruction generator so we added the call to instruction generator on top of our call stack what told us Phillip that we were ready to pop the call to instruction generator off our call stack the return so we exited instruction generator and returned out to global we knew that because when we got really instruction generator what was taught well it was global perfect it was global returned back out to global and what happened to our execution context it was done gone clear finished the only thing that stuck around was the function we returned out all right because we returned it out and give it a new global label generated generated funk so as Lewis said I now want to run the functionality formerly known as x - I don't panic even though x twos label this was deleted this is gone I don't panic because out here I have a new label for it generated funk so talk me through that line Z we now hit our line the call to generated fun talk me through it what happens here is he under his new label and we're going to assign the return value of this function to watch global variable variables are perfect for now resort is passing three and so for now resorts are defined and we're calling generated funk which is performing more by to visit of three we create what I new resolution card a good excellent there it is a new incision context into it we go and the first thing in local memory Z is what now so again it declared the variable now Nam an assault will declare the variable V background parameter and assign of the value three excellent very good ok and then we do what numb by two or something for returning so we'd better return out six into result excellent there it is folk this is this is very strong what have we done here it looks pointless to me why did we do this what are we done here we have created a function instruction generator there it is we put we create a placeholder generated fund which is going to be whatever comes out the bottom instruction generator could be the number three it could be a ten what could be a function well we're gonna find out we call destruction generator we go inside what's it tell us to do tells us create a new function x to do we run it no instead we grab it the whole difference in return out store it in generated funk now we have that functionality formerly known as model our two in a new global label generated func meaning we can now call that functionality out here we can run it by its new look they generated funk but it's really just a functionality of x to take in num-num by to run it taking three return out six into results let's have thumbs on what we've done here before we do that let me ask you this what if I put parens on the end of this x to hear what would happen instead their median it would have invoked return to the return value very nice so let's think well let's play that through so foot parens on the end let's more put an argument so we're gonna have Nam is going to forward to undefined undefined by two is not a number I think and the end I think so we're gonna therefore return any end from instruction generated not a number so generated font will be na n and so down here will have not a number trying to be invoked and finally we might get an error at that point this is one of the challenges of java scripts way of handling datatypes rather than restricting the so obviously no no no i want this to return the function so you can't return anything except for a function it goes no problem very happy your water to another number this seems very reasonable idea right now and then it only when it finally tries to run it four lines lane fall so the steps later does it finally spot it's why error handling and jobs are gonna be hard it was a little typescript that is a more restrictive version of javascript that says are you've got to specify your data types is your inputs your outputs what particular variables will be and do not try and modify them otherwise you will have trouble alright so nevertheless here my biggest question my biggest is two thumbs i have a something i want to see people spot which is well let's do fun you lost me i'm clear several stones finit has one so there was carnation why are we doing this it seems like it's repetitive to declare a function inside of a fox and then return it out just to call it why are we doing this why we declaring a very usefully explicitly named function what why - inside the mother functions then returning a little baby function out and then calling it again anyway well just declare x - in the global memory from start well it turns out we're going to get a whole bunch of bonus features by return by declaring by defining by storing our function inside of local memory and then returning it out we're going to get a whole bunch of bonus features attached that function will see all to come all right for now let's talk about this calling a function in the same location the same scope the same education as it was defined let's walk through this code line by line but note we're going to call outer there inside which we're going to define income account and immediately call increment counter inside the same location okay let's walk through this code line by line and it's going to leave us with an open question and I'm the qeh T which I regrettably have given the answer to here but we're gonna pretend we don't see this we're gonna feel that I'm a guilty and see what it tells us about how our scooping power javascript thinks about looking for the relevant data at the relevant moment okay what data is going to be available to us at a particular moment and once we know that we're gonna have a very clear model for how we get this beautiful concept of closure okay line one Scylla what's happening so let's start by declaring a function in powder yeah with no parameters stored in the global memory okay next lines gonna so we're going to call out okay perfect way from no arguments and then opens I've been very good thanks Kyla and we're gonna add that to the call stack there it is the court outer splendid but whatever user for but okay in the execution context of outer we go and Z what is the first thing that happens inside this execution context we declare a variable perfect declare counter set it equal to zero okay next line region we're declaring a function called increment counter in the local memory perfect that is excellent that median next line meetin we are then calling increment counter okay okay it cooling increment counter have an on-call yet Miami meter parentheses does it need an argument no it doesn't the parens are my all-powerful thing they create my execution context alright so I'm adding you can encounter the top of the call stack the stack of my functions being cooled I'm doing I'm calling out set of holding increment counter inside of outer so increment counter gets added to the top of my call stack alright integracare do we go one is the first line of code for that that we encounter any grooming counter counter plus bus counter plus plus counter plus plus okay so we better increment this counter but we've not declared anything inside local but we are going to look there for this thing we're referring to counter so where do we look for counter first for it we first look in local memory the local memory of the local institution Pollitz we find it no no we do not so where do we look next major we'll look in the local memory or our aha where do we find counter yeah we do what we do to it beautiful we did not find that counter in our encounters execution context local memory so we set one layer out to outer everything right now I am so confident I am so confident that it's because I called increment counter inside of our sub so ran it inside about one layer down the call stack that I went out to out of it I'm so confident of that I'm hundreds n confident that that's the reason it's obvious that the box inside a box and 110 confident the reason why I have my counter available to me in increment counter it's because I'm calling increment counter inside of outer it's going down the call stack everyone caught it with me we're all wrong I try to include myself in that base we're all wrong together well it says here where you define your function where you define your functions determines what variables will function that sits when you call the function in other words it's not by hold increment counter inside of outer it means when I don't find counter I can go one there out to outer if I encounter topic hold it there it's because I did find increment counter inside of outer it's going to find it adjacent to counter well for now who cares that they're calling to find the same place anyway so I can't even tell I'm you actually may still be right you may realize you may still be right we'll see well can anyone think of a way to somehow test this to run increment counter in a way that would test my theory that it's where I call it that matters for that we can return the definition of increment counter how about her well it's a very very sophisticated JD we can call it outside about aha we can call it more yeah absolutely further your so so long but you're right right JD see we can call you come encounter out here then I know I define the inside but I'm calling it outside so I can see what really matters easy worry define it think encounter where I hole it so how do I end up running into the character out here I don't think I can do this whatever idea yeah well if I run into my character I think I even run it like this median is this legitimate code no yeah I'm gonna get some sort of error on tight include encounters not a function it is not available yeah so meter how could I get that inner increment counter function out from where it was defined and test my theory of it's where I call my function or is where I define my function that determines what data ends up being available to me IVA could return that fashion the powder and that's it I can return that increment counter function out from where it's defined we gave birth to an insider here tower let's return it out and use it outside just as we did with our instruction generator the multiplier to which we we define it slightly returned it out same thing we could define increment count and return it out give it a new global label for that funky in the functionality and then cool it by that new global label in global exclusion context here it is there is a way to run a function outside where it was defined return the functions definition and assign it to a new global label for that functionality here we go folks this is this is a cool is that code this is at code so line one what are we doing Z memory those are legitimate thank you thank you thank you next line region we're declaring a variable my new function yet to be defined it's so Joshua doesn't call it yet to me to find it cause it undefined yeah that's actually a datatype in JavaScript it's always like video so yet to be defined very well poetic version of undefined alright undefined and we're going to now go do some work right median to figure out what to store that creating a new local execution context because we already poking the function powder excellent very nicely put by median and the return value of this function called out return are being stored in this mighty function label whatever the return value is could be a number could be an object to be an array could be a function whatever if we're going to find out all right so we're calling outer meaning within the pool meaning it gets added on top of course at perfect we create an execution context which realization context that will run the code of outer for us there it is and here we go and the first thing there's no arguments and what is the first thing we do inside of our local memory Louis we're defining a variable counter setting equal to zero excellent thank you this the next thing we do Scylla we declare a function you can encounter in that local memory excellent perfect there it is now do we invoke that function no what do we do instead for we return the value of we commit counter right function value you don't think it's sort of running increment counter over time it's returning the functionality which is weak which is legitimately known as a function value this is our label for our function value but think of it as being the function definition is the value right bits were turned out the whole function definition is going to be returned out not executors we were turned out in one go think of it returning out basically function and what supporting that function for that counter pots box yeah exactly that's the functionality we're returning out that's the functionality we're turning out into what global variable for mine if I enter my new function excellent so my new function is now all this functionality it's now this functionality here okay excellent so how has returned that function formerly known as increment counter now it's known as my new function and it was formerly known as increment counter but not anymore that was just its label inside or outer what's happened to our destitution contents at this point region it is white it's white posh word for that popped off the call stack and only the returned out function for me knows increment counter is held onto in a new global variable my new function or is it it is no it's not that you guys will see we'll see what's our next line of code because now we can run our increment function in the global context from you label my new function there it is so we hit the all-important line my new function being run the all-important line alright skip my new function being run and what do we do Louis excellent that's where we begin as always yeah in we go and it has a local memory thread has a thread by the way is woven in here come back out and now it's gone in here ok can we go and certain context what's the first thing it says to do inside of my new function the functionality formerly known as increment counter what's the first thing it says to do increase counter go perfect counter plus plus now and how we get our question where oh we're calling my new function so what we do with the call stack for it we push the car to my new function to the cost excellent we're support of my new function to the course at very well-put it's top of our course tab this is where we are right now it's down to the execution context still open no no no no no this is so I forgot to do my forgot to indicate that this is so darn that's sound more cuckoo than intended this done gone we're in the quarter my new function form line of our code here immediate where do I look for counter it turns out it's not in battery because that's a good answer yeah we're first first in the locker room right I've always taught my course at first and do I find it medium no no I don't so now where would all of my intuition who my everything tells me where do I look next well your intuition would probably tell you to look down the Casa down the call stack into global because I'm calling my new function in global where else would I look where else would I look I couldn't feel where else I would look but then it's very obvious than the next Bateson Lucas cool do I have it there is there a counter can i hey what a bad design language that allows you to find a function and then run it and then the values aren't there so what would we get here what would our intuition tell us that we get here Scylla yes some sort of error has tons of error you know I did not find your counter I'm sorry so why do we do all this why do we do all this what a waste of time well it's Sunday what a way to spend a Sunday unless unless something else unless something else is actually happening tell me we do not yet have a model for and isn't the else is happening what my that thing be well I'm not gonna drag it out longer than I already did because I already dragged it out quite some time what does that mean is actually happening it turns out that when I return out and there were baby function from a bigger function when I returned that function how I get more than just the function well I returned out that increment counter functionality and give it a new global label my new function that can then run with counter plus plus inside of it I don't just get that function now I get something else I get a not I get the live data from around that function when it was defined I get that whole live data returned out on the back of the functionality for we know does increment counter on the back of it returns out that live data we're going to add some caveats to this but for now we've therefore counter to zero and increment counter is a function I get all my life data out on the back of the function as I pass that function out into my new function out returns with it a backpack of the live data from when from when this function was defined when this function was defined we're an outer and it we went we create a counter a zero store that live in memory not counter might be 0 literally count now zero memory Engram encounter is now a function stalling memory when we return now to our encounter we brought with it all the live data from when that function was defined all on the back while fanning from account functional functionality so attached out of my new function is that back pack of live data on the back of the function meaning median what actually do you think is the process when I end up calling my new function the function with the backpack of data what actually do you think is a process when I do that and are looking inside and I hit the lion counter plus plus where do I look first median inside the backpack where do I look first excellent and where do I then look next medium before global into the backpack these are the same thing just copied asserting in two places into the back where what do I find median the counter variable to told one fantastic all right we're going to talk so much more about how this works but first now I finished writing my new function what happens to its local memory into its execution context delete it popped off gone this guy here is done it's local execution context marionette so returns me out it's done but we're going to hit the call to mind you function again let's do it rather call my new function again we popped it off the call stack its data unless you return to me out is deleted as all function execution context data are when you finish running them okay well we're gonna hit it again my new function is cooled again sky that what happens so you go into what was before you give me calendar yeah his execution context is created yeah and then you grabbing a local memory you increment count right so you hear that first-line counter plus plus and we're Phillip do you look for counter first look in the local variable environment you can local memory local variable environment folk variable environment is a posh name for that memory of data receive it's the environment meaning the things around you all available variables do you find counter no no we didn't declare anything inside money function no counter now where do you look next for that you look in the backpack into the backpack of that day I would he find can which is one he start around he's stuck around what do you do to it in community to to to our live data on the back of the function has stuck around attached and persistent to that function definition where is our local memory bomb attached to the very definition of the function is a persistent store of live data so that when I call my new function I don't find the the variable I'm looking for in local memory I don't need a global first I go off to my backpack of live data attached to me in other words rather than going straight away rather than anyway somehow in here appears my backpack of live data only then after not finding it there when I look out to global next all right but I think we can see this has profound consequences my function now has data that can stick around between calls between in vacations my function has a memory it has a little store a non-cash associated the definition of it bundled up this allows us to profound things we're gonna see in a minute but first thumbs there are a ton of clarifications it can be asked on this I don't bring them up but I always want to see if folk can raise some interesting paraffins you lost me unclear I have clarifications meet an avocation zis clear skies Caucasian Phillips fabrication Louis's clear median kick is off so you mentioned that there's a backpack that gets returned out with the function with this internally defined function and so my question is whether that backpack comes into existence when the function is defined inside or whether it finds out on the return what a fantastic question what a fantastic question median salute here's how it works the moment I increment counter function is defined never together when I write when I went up sees the word function come encounter never forget is literally it's a command to JavaScript to take that label increment counter and take its functionality and go store it in memory never think it's like I already said think they were just there I never grabbed and stored in memory label plus definition and at that moment that's ground a bit of memory at that moment they also get a hidden property a hidden property which is a reference built into JavaScript square bracket square bracket scoped square bracket square bracket which is a little hidden link to all the surrounding data from where that function was defined so as soon as that function is defined it gets a bond to all the surrounding local memory at the moment definition region and it's stored in a hidden problem we can't by the way we cannot console.log increment counter dot square bracket scoped square bracket or you know increment counter console.log and see this we can't do that this is a hidden property there is no console logging of it it's a hidden property but it is a bond function definition all the surrounding data meaning when that function gets returned out that bond persists out returns the inner function and with it that bond that hidden scope bond to the surrounding data is pulled out as well via that scope reference to the surrounding data so it is just a link this little bond surrounding didn't mean when that photo gets returned out it's gonna bring it's gonna pull that with a bomb and put it out with it there's also question reader yes the implication of that would be that no matter where you call that function inside of the outer function or in the global execution context it's dealing with that same that bombed that's where it goes in loops yeah so you could potentially call it once from inside outer and once from more easily King is always looking down this route first but most of the time we don't really notice it right because normally when you're calling a function inside of here the the coolest that chain give me a call you in the same place in you to find it so you don't really make so it becomes interesting when I returned the function out and the local memory would appear to have gone but it still held on to through that bond and normally whenever - when I finished running a function anything that's not returned out is deleted but now job suppose I've returned out of function and it's still got a bond a reference the surrounding data I better not deleted me that data better stored in the back hypothetically though we were to call increment counter right before you return it out of outer and then you run my new function the first time in the global context it would be seeing a counter it would be seeing the value of one individual and then it would be that's all the same it is a backpack of live data absolutely okay thanks a great question major foot is very similar to medians but slightly different when the backpack is created and it's creating that link between the variables and the function does it reference variables that aren't used in the function so I guess that commendeth yeah I mean that bond is - that low live local memory of data everything absolutely but when I returned that function out suppose I define 100 variables inside of here by know exactly I can only access a battle it's really clear once I get this function out and call it my new function I get only access this bag of data from inside of my new function I can't do my new function dot scope counter I can only access it by referring to something that's not a local memory and therefore going and looking in the backpack of live data otherwise I class is it well that means when I return that function out into account into global variable my new function with the bag of data I can know before I return out that function or as a return I can know exactly what things in my local local memory or my backpack the same thing I could ever return refer to fill it what's the only thing from my new function that I can refer to my back counter so suppose I defined a hundred different variables in here today with tunnel memory would they be my backpack I mean yes we haven't said but JavaScript engines are smart enough to think hold on I know exactly what's the only thing that can ever be referred to in the backpack in its counter so I only hold on to stuff in the backpack that could ever be referred to don't be returning out at the point of returning out and the function javascript is an optimization goes we just check what's in that old counter well then everything else in this backpack delete it only hold on to data that could ever be referred to from that function call all right Skyler your clarification just answered it excellently well I'm impressed and none of you have any interest in knowing what this backpack is technically called or maybe you just assume it is called the backpack because why not what are useful I need to return for it but we do not have the privilege of setting JavaScript official terms for them so instead we have to acknowledge at least their official terms that is - I like not very catchy long in fact very long one is well first I want to tell you the meaning of the word lexical lexical means the positioning and ordering of where I am it says like they're ordering things on the page and when they defined this is known as a lexical scope reference because I've defined increment counter here inside of outer and therefore and it's definition time I'm making a bond through this scope property to its surrounding local memory it's called a lexical scope rounds because it's about where I positioned myself here inside of that local memory I position myself it determines where the bond is to lexical means that where I'm positioning myself in order sort of word order almost so I'm positioning myself here I got a lexical scope reference well when I return out that function into my new function a function formula to encounter that lexical scope reference persists so we can call it our well persistent lexical scope reference catchy alright another posh name for it is we often call our mobile memory a variable environment the environment of available variables around you the things around the variables around you well some people say this variable environment is kind of closed over and returned out when we return out the function we close over the local memory the local very mode and return it out in the backpack so we can call it the closed over variable environment and now do you see why I like the name backpack but there is another colloquial name I find very confusing because it's of the name of the whole concept this backpack is colloquially called the closure people say put it in the closure persist our data in the this backpack here is called the closure these are all words for that backpack of life data that is now attached to the definition of the function my new function that got returned out from where it was born as increment counter closure is one name for it but people the whole concept closure so I don't like this but people calling you've got to know that of course by a pack I think is a very good name but obviously cannot endorse it as officially I warn you against using it in interviews even as it spreads even as it spreads even as we spread this term I recognize his limitations man persistent let's go reference very impressive clothes of the very environment very nice all right so there we go folk we're gonna talk in a moment about how is it going to change how you write functions what's an empower to do we're gonna also talk in a second about one edge case that wasn't brought up once or the situation that wasn't brought up what if I ran powder all over again generating a new returned increment counter function let's see what happens with that if I ran it all over again all right how again is stored the returned increment counter function or definition into another function and then we'll call another function a few times here we go we're gonna run out to one more time we are almost there we are almost almost almost there so let's run out of one more time here we go so let's move our cool stack over cool stuff it's over here with global and we are going to hit the line another yeah another function it's going to be the return value of a further pool to have sir so talk me through this Z left hand side first we're declaring a global variable call another time another funder special yeah if I could be what's right out another function okay yeah and do we know what's gonna be stored away yet see it's gonna be under five under five now because we've got to go off and get the return value for calling outer so let's do it let's create a new execution context here we go and what's the first thing in our local memory Z it's a Claire a local variable cloudiness and and we set it equal to zero this cavities yeah fine ass the same person same question every time the next line the immediate next line then we're going to declare a function called increment counter perfect okay and now is that what we're doing at that point meter so that function will also get a persistent let's go right Wow Wow very impressive so we are instantly on the function definition moment making a bond from it under the hood through this scope property to the surrounding local memory very nice from me too okay now what's the next line we hit me to the functionality all being recounted yet a function of encounter return it out into what global variable another function and are we just returning out that increment counter functionality no we also persistent excellent is an excellent if you also get a persistent and ethical scope reference our returns for learners increment counter and not anymore out returns and with it okay okay so at this point I'm gonna ask my favorite question to ask what if we were to pull one of your words are cool another so another function is the function there it is that we just returned out with its back right it what if we were to cool my knee function once my knee function again another function once another function again median what if we were to do that what would our values cool mighty function ones and that's slightly change this so that we can console more guy counter after we increment it so it count Plus Adam we consume log it mighty function wants mighty function again another function wants another function again what values of counter would we see in our console for each of those calls are we starting with my new function okay so that would I think we left - well we're gonna run to the very voice tell through the first name okay so you would see it incremented from zero to one over it and then from one to two okay - in the console but then when you switch over and run another new another function you're starting with a variable in its own persistent you're starting with its own only use you get and so you'll see one and then the zoo - yerevan round applause excellent very beautiful we have now got two distinct functions that we returned out individually formulas increment counter more than one function one another function and they both have their own distinct back pad our functions have individual persistent memories caches of data attached to their definitions all right thumbs at this point you lost me I'm clear I have clarifications it's okay there provocations okay to have funds any final convocations people all right by the way this is known as a lexically scoped language one in which where I defined my function is what in the end always determines what data I've access to and we take advantage of that feature to give our functions persistent memories attached to them this is a quick clarification a dynamically scoped language will be one where I call function is always what determines what I have access to so I'd go down my call sack always never checking in some backpack so given we have this feature this persistent lexical scope references bundle of data this backpack this closure attached to our function definition what can this let's do this let's has achieved amazing powerful functions functions with memories now enable us to build functions like the once affine version of a function so the one to fight version x 2 says first thing from me taking seven return out 14 and increment in the backpack a value of counter to one next time you run me make sure you're checking the value of counter it's a 1 you can't run me again and Dussehra departing in your pass in 22 more point 1 4 1 2 5 version 1 by 2 parts in 20 check in the backpack fine count as one you don't return out 40 you return out well you can add different versions you get one which returns out the original value 14 or another which returns out sorry you curly rummy once and this turns out to be super useful you're building games a tic-tac-toe game you want to be able to unclick change the cells value but you never wanna be able to add again then you set your function you set your phone you said a one to five version of that function sorry once you set the value of the tic-tac-toe cell you can't tell it again you're only allowed to run it once all memorization memorization is super powerful very very standard practice to using your code you're a complicated function that takes a ton of time to do its work I say finding the nth prime number or some other thing that takes a lot of time you pass in I know 10,000 12,000 and find the 12,000 the prime number can take a few seconds well do that work and then stall in the backpack maybe an object like store and have 12,000 associated with whatever the value is that it's a 12,000 prime number go do the work of finding the 12,000 for a number the first time and then make sure store in the backpack so the next time when you run memorize nth prime the end prime with a memory and pass in 12,000 instead of doing although you know figuring out the 12th and the prime number jump straight to the backpack check first if you run over 12,000 before and instantly return out the value from the first time you ran it my functions now have memories and that is very powerful and there is the module pattern and is used in many design patterns in JavaScript the ability to bundle up state data hidden on function definitions when you write again large code bases thousand tens of thousands of lines of code hundreds of thousands of code many develops on the team its pre-prom attic to what's called pollute the global namespace pollute the memory by putting like result is seven but you want more data in your application to last sometimes the whole life of the application it's like like schools of a game you don't want to have inside of functions only when the function really finishes running they're deleted at some date you want to hold on for the whole life the application player scores now you can be really care with how you define those variables but it's still pretty problematic to have in the global memory result one result - and the only way to keep data around the entire life of an application is through to be in global memory also we thought what closure also gives us is the ability to persist data for the life of an application but hidden in backpacks one function definitions and we write those function definitions in smart ways such that we can pass in a value which will then be stored in the backpack and we can write them so they return out the value for some return counter so we get right read access to data but they're all bundled up inside the bundled up inside the backpack of a function not they're able to be mutated you can't do my new function counter you can only access it through this very nice interface that is I can run my new function pass something in that I'll make sure it gets passed to the backpack I can also make sure when I run that function when the return value is all the data from our backpack and this is what gives us something called the module pattern in JavaScript right people excellent there we go that is closure
Info
Channel: Codesmith
Views: 13,560
Rating: 4.9913421 out of 5
Keywords: javascript, learn to code, learn javascript, programming, coding, fullstack javascript, software engineer, learn code, web developer, web development, react, redux, node, coding bootcamp la, coding bootcamp ny, coding bootcamp nyc, software engineering, intro to coding, learn coding, advanced coding, advanced javascript, hard coding, closure, scope, execution context, closure javascript, scope javascript, execution context javascript, hard javascript
Id: XTAzsODSCsM
Channel Id: undefined
Length: 57min 4sec (3424 seconds)
Published: Wed Apr 01 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.