During this online workshop recording, Sam will go under the hood of JavaScript, so you can confidently tackle new problems and work through blocks. He will also spend time working through the CSX Challenge: after, with participants.
Sam will cover:
– Understand how closure works under the hood (one of the most misunderstood but most powerful features of JavaScript)
– Understand core JS runtime features – execution context, JavaScript execution model, and the variable environment
– Be able to wield, optimize and debug popular pro utility functions like once and memorize
– Be able to implement the module pattern – one of the cleanest and most resilient design patterns in JavaScript
Join us for live workshops every week here:
Learn more about Codesmith here: codesmith.io
Stay connected to our community!
Codesmith:
Learn JavaScript for Free:
Free Events & Workshops:
Follow us to stay updated!
Facebook:
Instagram:
Twitter:
LinkedIn:
#learntocode #javascript #programminglanguage #recursion
[Music] Thank you My name is Sam welcome to JavaScript the Hard parts thanks Ryan Tonight we're going to talk about Closure Closure is a very very difficult concept For a lot of people to understand I have Worked personally with senior Engineers Who have 10 plus years of experience who Still don't know what closure is or Really how to explain it effectively In short what it allows us to do is it Allows us to give our programs Programmatic memory We can we can build functions or Programs like once or memoize if you're Not familiar with what those are once is Essentially a function that knows when It has been called more than once and it Will not execute if it isn't the first Time it's called If you think of a video game if you Think of the first time you do something In a video game and you get a bonus Amount of experience Um that is a once programmatic function Built behind the scenes There are a lot of JavaScript design Patterns that utilize closure most Commonly the module pattern If you have ever used a library or if You have ever exported a snippet of code From one file and imported it as a
Module into another you have exercised Closure You can also build iterators and Maintain state in an asynchronous world If you don't know what that means it is All good All you need to know is that closure Allows our functions our programs to Remember things even if they get lost They hold on to the data it persists Persists is a really great word I'm Going to write it down Persists Okay Closure That's what we're here to talk about Before we dive in we're going to talk About JavaScript as a whole and the Mental model that we hear at code Smith Stand behind and we're going to diagram Through some code together Let's talk about the principles of JavaScript that we all need to be on Board with before we move on to Understanding how closure works there Are some pillars in JavaScript that are Really really important to understand Before we can dive into actually Executing and talking through code One of these things is a function A function is code that we can Define And save and that we can use at a later Time To do something
To carry out an action You'll hear me say function definition You'll hear me say function label And you'll hear me say this function is Executing or being invoked We'll get into more of that as we Diagram through code but functions are Chunks of code that we can save Somewhere in a label And execute later on to carry out a task The threat of execution JavaScript is a single threaded language That means when JavaScript is read or uh Interpolated in the browser or whatever Environment we're running it in the code Is read by our machine top to bottom Left to right Like a book or like a piece of paper if You're reading in English left to right Top to bottom The threat of execution goes that way Memory Any cats fans out there uh memory is in Its simplest form a place where we store Stuff We can get more granular if we want to But for the purposes of it tonight all You need to know is that memory is a Devoted space Where we can store things Any questions about these three Principles Okay All right this little chunk of code
Let's talk through it we're going to Examine these three principles talking Through this chunk of code Would anyone care to be my guinea pig to Technically communicate through some Code I promise I will help Alex amazing thank You so much for volunteering awesome so Alex uh is this your first hard parts No okay okay so then you might have Heard some of these things that I'm Going to ask you about before so in Order to execute code we have our Global Execution context I.E the space where Our code will run there are a couple Other things we need to execute this Code do any of them come to mind looking At this diagram yeah so we're going to Need our Global memory 100 we will need Global memory or a Space to store stuff at the global level Great it's our variable environment and Uh on the left we're going to need our Call stack yes 100 our call stack our Call stack is a data structure built Into the JavaScript runtime that keeps Track of something that is very Important what does it keep track of Alex uh it keeps track of our threat of Execution and on the call stack our Threat of execution always starts with The global execution which is always Starts on the top and is always on the Bottom there thereafter 100 thank you
Alex excellent excellently done so yes Couple of things our call stack When we're running a program always has This Frame at the bottom which is called Global I.E we're in the global space yes It's what tells our threat of execution Or Toe Tells our toe that it needs to be in This space expertly done Alex thank you Thank you thank you now that we have These things set up we have our Environment variable our Global memory We have our toe in its right place and We have a global call stack frame on our Call stack Let's talk about code can you talk me Through uh what's going on in this code Snippet Alice Yes so we're going to start line by line So first we're going to look at keywords So we see let so we're going to declare A variable using let and the label is Going to be num And it's going to be assigned a value of 3. And where is that variable being stored I know that is being stored in the Global memory 100 which is the whole Variable environment for the whole Global execution context Expertly done go on then we're we're Going to move to the next line uh Looking for the keyword which is
Functions so we are defining a function With the label multiplied by two and That takes one input parameter Uh input number and well we're really Just storing the we don't even need to Go that far we're storing the definition Multiplied by two I'm kind of getting Ahead of myself you're totally okay so Just to replay what replay the expert Technical communication you're giving me We're storing Multiply by 2 right we're storing in This label multiply by two the function Definition Of multiply by 2. Correct so what is the next line that Our thread of execution will hop to Uh actually that So the next slide is going to be Looking for the keyword again which is a Constant so we're declaring a constant Variable with the label output And we are assigning that the value Which is the evaluated outcome of Running the function multiplied by two With the input parameter num Awesome awesome which we don't yet have So right so when we hit line six Alex And we see that we're declaring a new Constant called output and storing just Like you said the evaluated result of Multiply by 2 passing in Num What does it mean when our threat of Execution what will our threat of
Execution do excuse me when it sees that There are parentheses around this known Um so the threat of execution is going To invoke that uh function it's Basically saying to execute it and Within the parentheses it's the Parameter which it's executing it Using pretty much right specifically in This case num is an argument num is an Argument because the function is being Invoked but it's taking the place of the Parameter input number on line two Hundred percent correct so now we know We're invoking a function right we hit Line six we have this label output Stored in global memory and now we need To actually invoke multiply by two Passing in Num in order to get the Evaluated results to know what we're Storing in output Yes what happens when we invoke a Function in our execution context So uh the function gets popped onto our Call stack And a couple things happen when that Goes on Um before you get much further just a Slight correction push on to the call Push I'm sorry yes push on push on pop Off you go on you're killing me All right so it gets pushed on to the Call stack and it brings the threat of Execution from the global execution Context to a local execution context
Which is multiplied by two Yup 100 correct 100 correct so now our toe goes into This local execution context which is The execution context for multiply By two passing in Num Expertly done so now we have a local Execution context which has its own Local variable environment local memory Talk me through what happens inside of This local execution context So the very very first thing that's Going to happen in the local execution Context is it's going to look for Variables and the first place it's going To look is in local memory but there is None so the next thing it's going to do Is it's going to look in the global Memory and based on the parameter we see That num equals three so we can pass Three Into multiplied by two So now So yeah now that we have Um our num now we can go back into the Function multiply by two and we can see That num is equal to input number so we Are in the local memory declare an input Number equal to num which is equal to Three I don't know if I'm going out of order By the way I'm sorry no no no you're Doing great you're doing great keep Going
So now that we have the input number Parameter we look into the definition so We're declaring a constant which is Result And we're assigning it the value of Input number times two which is six Excellent And we are returning the results and Returning is basically handing the uh The variable result back To the previous the previous context Which would be in this case the global Or this case the the function which Returns it back to the global context 100 correct so then that's eligible for Garbage collection at that point Yes So we can pop it off our call stack And while and then when that happens uh The return gets passed into The global memory Which gives output The value 6 in the end I know again I'm getting Ahead of myself but you're okay you hope I'm not confusing anyone no no you're Fine I'm gonna recap everything but keep Going there's one more thing that Happens So next we have uh Another constant one second I'm sorry There's one more step so you popped the Call frame off the call stack we've Returned the number six into the label
Output Our local execution context has become Eligible for garbage collection where Does our toe go Oh so the the threat of execution goes Back into the global Execution context where it previously Was so we're back into the main code Body now essentially Yep yep yep absolutely expertly done Excellent excellent work Alex yes 100 Okay Take us through line seven let's go So now we are again always looking into The keyword so we're declaring a Variable which is a constant with the Label new output and we are assigning it The value Which is the evaluated output Of multiply by 2 With 10 passed in as the input parameter Or the argument I'm sorry You're totally fine so we hit that Multiply by two which is followed by Parentheses with an argument passed in So we know that we're invoking that Function correct once JavaScript begins Invoking a function talk me through what Happens again we immediately look to the Function body so uh we are I'm sorry so The first thing that happens is we go Into a local execution context nope Once again there it is And a few things are going to happen
Which is we're going to add it pop up We're going to push it onto our call Stack I'm sorry you're good We're going to weave our threat of Execution Back into the local execution contest That that just opened and the first Thing that happens always in a new local Execution context is we look for Variables so is there a local variable And in this case Yes there is Because We have uh input number is equal to 10. I dig it That's terrible okay read give me one Second Input number is equal to 10 yes okay So the next thing we're going to do is Look to the definition of the function And it is declaring a constant Which is labeled result And it is assigned the value input Number times two which is 20. Mm-hmm And then we are returning that result so Again we are Passing that variable back into where it Was called Previously and now that local context is Eligible for garbage collection We're going to pop it off our call Stacks those And we're going to weave our toe back
Into the global execution context Terrible terrible arrow that I've built I'm also going really fast but no no no No no no you're doing great you're doing Great excellent now what happens All right so This is a trick question Um Um we were back in the main code bodies So now technically we're we're I I hate To say we're done but like we're done With this yeah I guess okay cool our Program stops our program stops running Yes 100 excellent excellent job Alex Everyone give Alex snaps claps yes Expertly done awesome technical Communication so some things that I want To draw attention to right I'm just Gonna go back a slide because my Terrible handwriting makes this Unbearable Alex mentioned that and rightly so That this part of our function Has a very specific name Does anyone remember what Alex said that Is the function what surely I see your Hand up Definition 100 correct this is the function Definition and the difference between This function definition and what's Happening in these bottom two lines is That in these bottom two lines the Function is getting invoked
And the way that our threat of execution The way that our interpolator knows that The function is being invoked is because It is being passed an argument or maybe Not if it wasn't being passed an Argument it is seeing these parentheses Come after the function label Does that make sense to everybody That's super important okay cool it will Come up again I promise awesome job Alex Thank you thank you thank you you're Crushing it keep it up yes all right Another thing to think about as we start Moving towards closure and understanding Closure more deeply Functions oh we got a question cam go Ahead yeah quick uh question so I know When we talked about like when we spin Up a local execution context uh the Engine is I think we used like looking For variables Um I have a question about that part so How does that I guess activity work what Does that mean technically and also is That is that looking for variables Activity is that distinct from like when We just start our code we're in the Global context and we're like uh Initializing our variables in the global Memory are those different activities Does that make sense I think so can I Play back your question to make sure I'm Understanding correctly you want to know The difference between initializing a
Variable And actually calling on that variable Like where when do we look for it in Global memory versus when do we actually Create it I think so keep going and it might Okay Okay cool so the only time that JavaScript will ever check for a Variable is if a variable is called on So in our code Like Alex mentioned JavaScript sees this Keyword let and goes okay we're making a New label so here's this new label and Here's the value that we're assigning to That label great This is basically the same thing here's A new label and here's the value that We're assigning to that label this Function definition We come down here okay great here's this New label And the value that we're assigning to it Is the evaluated result of this function Being invoked passing in this thing numb When JavaScript sees num it goes I don't Know what that is Let me check the global memory and see If that means something if I should know What that means it will see that earlier We said num is three it will take that Value And invoke the function using that value As its argument Does that answer your question
All clear thanks of course for sure Great question Okay cool so we've talked About Um Global execution context the global Variable environment the local memory The threat of execution the call stack All these principles of JavaScript that Help us talk through code and what's Actually happening under the hood now Let's talk about some more like little Finicky Concepts that we can play with As Developers Functions can have multiple names what Do you mean Sam We just talked about this there are two Parts to a function declaration right There are two parts the label I.E what Are we calling this function and the Definition What's happening behind the scenes in JavaScript is that this function The label is really holding on to a Reference or a pointer you may hear it Called the label is holding on to a Pointer that points to this function Definition So we can call this function And store the evaluated result in a Variable but we can also take the Reference to the definition And store it in a variable What is the difference between what's Happening on this line and this line in The code can someone tell me
Hint we already talked about it As far as code goes like what is the Difference between these two lines Adrian Well on the Output line uh you're invoking it Because of the parentheses as well as The number being passed in 100 correct what are we doing on the new Label for multiply by two line uh we are Uh declaring a variable using the const Keyword labeling it new labels for Multiply by two and setting it to the Function definition of multiply by two Expertly done yes the function the Excuse me the function definition 100 Percent so let's look at this in code Anyone want to talk through some stuff Will I see you clapping does that mean You want to go Yeah Excellent totally cool go ahead unmute Let's talk through it um we know that in Order to have a global execution context We need a place where we can store stuff That is called what Um we need the call stack yes we do need The call stack for sure that's not what We're talking about uh well where would We store stuff like if we want to Declare a new variable oh in the global Memory 100 correct Global memory I don't Think I'm gonna get all this right by The way I just wanted to walk through it
In case like if I have questions Um I could just ask you no if if Everyone knew all this stuff already why Are you here no this is great so true Yeah okay good so we have a call stack That call stack allows us to keep track Of where the what is Um The Throne of execution correct Keeping our toe in line yes and as Alex Reminded us the bottom most frame on That call stack is always the global Execution context that's where we are Great well talk me through this code Line by line what is the first thing That JavaScript is going to do So the first thing we're going to do is Create a new function which is going to Be called multiply by two and that is Going to take in a input number 100 so what is Javascript going to do With that information Um it is going to Um It's going to Well oh like where is it going to go And uh it's gonna put that into the Global memory right 100 correct so So we're setting up a new label right Multiply by two And stored in that label is going to be What or a function definition 100 Correct yes our function definition Where is the next line that JavaScript Thread of execution where are we going
To go next Um I want to say uh so we go to the Constant output variable 100 correct Remember we're not invoking this Function yet so JavaScript JavaScript isn't this rude but it Doesn't really care it doesn't care what The function is asking us to do because We're not using it right now which is All that code that is the definition and Storing it in this label for later so You're absolutely right we're jumping to Line five talk me through what's Happening Um we're declaring a new constant Variable called output and output is Going to be equal to multiply by 2 Um when invoking the input number nine So that the result of multiply by 2 and Taking not awesome stuff where is output Going to live on the global memory right So we're setting up a new label called Output and you're absolutely right it Will be set equal to my favorite way of Saying this and it's kind of like a Little Flex so forgive me but hey Chris Use it yourselves the evaluated result Multiply by two passing in the number Nine awesome job okay so we hit line Five we know that we have this new label Output in our Global memory and it needs To be equal to the evaluated result of Multiply by 2 passing in the number nine
JavaScript goes oh wait okay I need to Use multiply by 2 now what happens next So it's going to jump back to the Function definition of multiply by 2. Um And it's going to Um Find our constant result or it's going To declare Our constant results In the function definition and which is Going to be equal to our input number Multiplied by two yes 100 correct before We actually begin carrying out executing The function JavaScript needs to know Itself that we're leaving the global Space right into a new space so what Happens before we even start any of that So we're going to go to we're going to Move the thread of execution to the Local memory right To the local execution local execution Context that's what 100 yes keep going Um and then I guess in the local Execution Memory it's going to take the the Constant result 100 correct there's just one more step That happens before that Um How do we keep track of the toe how do We keep track of where we are Um the call stuck but we need to tell The call stack that we're no longer in
The global execution context right how Do we do that Um I guess the threat of execution would Move from the glory like Um I don't know what the word is it Would move it from the global cost act To the local execution context you're 100 correct there's this funky thing That happens where JavaScript does What's called it pushes a call Brain Onto the call stack so it's essentially Saying oh wait We need to execute this function so JavaScript before it does any of this Work goes okay to keep track of where I Am I'm going to add this thing on the Call stack called a frame and by adding It I mean push push equals add I'm going To push this call frame onto the stack And under the hood It's usually Represented by the name of the function Itself so now JavaScript knows okay my Thread of execution is in whatever's on The top of the call stack I see right of Execution is now inside of multiply by 2 Passing in the number nine So now And now we can keep going Okay so so it's pushing a new Um Another thing is uh is pushing multiply By two into the global call stack but
The thread of execution is moving to the Local execution within multiplied by two Is that is that what's happening sort of You're 99 there just one little Correction we're not pushing multiply by Two into the global call stack we're Pushing multiply by two onto the call Stack And we're exiting the global execution Context we're going into a local Execution context okay Yeah yeah yeah That makes sense okay so one now we're In this local execution context where We're actually going to carry out the Invocation of the function so we passed In the number nine the first thing that Our function is going to do is what talk To me Um it's going to go into the function Definition In the local execution And then it's going to in the local Memory I think it's going to declare the Constant variable result which will be Equal to the input number that we're Taking in with um Times two which would be 9 times 2. yes 100 correct before we declare result Though this is a little tricky thing That happens in function definitions Okay input number parameter it's called A parameter on line one is a placeholder Our function needs to know what that
Input number is going to be as it Executes okay so the first thing that Happens in our local memory Is we decide or the computer program Decides what input number is In this case input number the argument For input number was passed in on line Five what is that input number Um nine 100 correct so before we even Start executing our function JavaScript Goes oh wait we need something input Number that's nine okay now on to line Two repeat what you said because it was Spot on Um I said uh it's going to declare the Constant result which is going to be Equal to nine times two because Um the input number yeah but well which Is Uh like oh was it equal to 18. thank you Okay You're good Okay cool so I'm gonna pull In a calculator for that one totally Fine so we've got Um the result being equal to nine times Two and then what happens on line three Uh it's gonna return our result Um To like out of our function into I guess I'm kind of getting ahead of Myself I guess no you're not keep going Okay it's going to return our result Which will be 18. Um out of the function into our constant
Output and it's going to store that Variable back into the global memory 100 Correct expertly communicated now now That the function is ended there are Three things that happen what happens It's going to erase the local memory And the threat of execution is going to Move back into the global call stack and It's going to I don't know what the word Is it's going to like remove the Multiply by two frame From the global call stack I don't know If I got the order of all that right or I think some of that was right I don't Know yeah 100 the order is a little bit Inconsequential because it all kind of Happens almost at the same time okay Pops the call frame off the call stack Pop pop pop is the word Correct the threat of execution exits The local execution context and returns To the global execution context yes and You mentioned local memory being deleted A little adjustment to the technical Communication the local execution Context including the local memory is Eligible for what's called garbage Collection JavaScript oh we're done with this junk Leave it here in the corner until the Program's done running and we can throw It all out okay But awesome well amazing job everyone Snaps for well yes yes yes yes I do I do
Have um a slight not even a question but More of like a Um More like explanation of like what the Local ex like what's the really the Difference like there's a difference Between local execution and the local Memory but like as the local execution Context just like when like that would Be like when the function would be Invoked and then the local memory would Be like all the things being declared Within the definition and then Like the final thing that happens that Like returns it out of the function That's the end of the local execution Context that's sort of how it works yes 100 and you're getting into what closure Is all about and it's uh spoiler alert There's going to be more discussion About this but what you're asking about Will is Oh God can't write Scope So the thing about local memory is local Memory is everything that that local Execution context has exclusive access To So if we wanted to outside in the global Memory outside the global execution Context if the last line was like Or the next line excuse me was console Log Um result what would happen
Nothing exactly we would get undefined Because result doesn't exist in our Global memory it only exists locally to This functions execution context Does that make sense Okay awesome question excellent Excellent job will do you want to finish Up with the last two lines or would you Like me to pass it to someone else Um about someone else if you want I Think the and I understand what the next Two lines do okay you crushed it though Expert expertly done awesome awesome Stuff who wants to take it up from here Who wants to take the handoff from Will And talk through these last two lines What's happening Go ahead Shirley Um so on line six we're going to uh Declare a constant new label for Multiply by two equal to multiply by two Um the the function definition of Multiply by two so we're just gonna Um rename the function uh multiplied by Two amazing where are we declaring this Constant where is it being stored Global Um Global memory New label for multiply Sorry for my handwriting okay and we're Storing in it what remind me Uh we are storing in it um with uh the Constant new label for multiply by two And we're storing the function Definition multiple
Uh multiplied by two sorry correct no no You're fine so you're absolutely right We're storing in at the function Definition again because say with me Everybody there are no parentheses after This label we are not invoking the Function we are storing the definition Awesome job Shirley talk me through line Seven what's happening Um and then we're going to Um declare in goal memory the constant Fresh output and it's going to invoke a New label for Motorola by two uh with The argument 10. great so what happens When we invoke that function Um it's going to open up a new Um local execution context and Um that new label for multiply by 2 is Actually going to be uh pushed onto the Call stack and then toe is actually Moving into the local execution of Context Yes New label forgive my handwriting And our toe moves in to our new Execution context okay great talk me Through what's happening in this new Execution context okay so Um the new label is basically the same As multiple by two so the input number Um our argument is going to be 10. Uh-huh so that goes into local memory And then we're gonna go through the Whole function constant result equals
The input number times two so it's going To be 10 times 2 Um is going to be the result And then the return it's going to return Result as 20. And then um it And then uh after that return results Um it's going to Um Because Um fresh output is the evaluated result Of Um new label for multiple by two um with The argument 10 so it's going to pop Back out into the global execution Context and fresh output will equal to 20 and then it's uh and the call stack Um that uh Function is going to be popped off toe Is going to move back into the global Execution context and the local Execution contest is up for trustable Trust um disposal A hundred percent correct expertly bound And surely yes yes yes yes yes some Things little adjustments garbage Collection is what it's called when the Local execution context is ready to go And you mentioned that the return the Results of 20 will be popped out into The global execution context use the Word return just because pop is an Exclusive action for the data structure Like you call stack but yes 100 so what
Happened what happened here we were Talking about naming the same function Two different things right when we Reassigned the function definition of Multiply by two to this new label new Label multiplied by two What happened the function still worked Right it still did what it needed to do We could store that definition that Reference to that definition in a new Label and nothing changed Notice too that these results are Independent of each other So when we called multiply by two a Second time on this line seven It didn't have anything to do with this Execution or multiply by two The two execution contexts Are completely separate Okay Will question hit me So I guess my question is if you were to Just Um make constant fresh output just be Equal to multiply by 2 taking in ten And that would would that just uh it Would take in what the previous one was Like there was previous result and then Multiply that By 10 or what because like that wouldn't Be a fresh Because the function's already been Called before right But it would open up a new execution
Context it would do basically the same Thing that we're doing here but just Showing you that you can rename a Function By okay welcome to a new label okay I Guess I was just wondering uh like the Function of what we're doing right now Yeah I'll show you in a little bit okay This is basically to let you know that If you rename a function it will still Work Okay so when we get to closure you'll Need to rename some functions in order To achieve closure and under the hood This is what's happening when you rename A function Cool I appreciate it Okay Here we are We've talked about how JavaScript kind Of works with these principles we've Talked about uh relabeling a function or Having it be exist under two different Names now we're going to talk about the Actual thing of closure before we do Please feel free to take two minutes Grab some water use the restroom we're About halfway through we got another Hour hour and 20 minutes to go I will be Back on camera at 41 past the hour it is 39 past the hour right now I'll be back At 41. grab a drink use the restroom Join me in two minutes two minutes
All right all right all right I'm back Start making your way back if you can Hear me Give you all another 30 seconds Excellent excellent excellent How am I doing so far am I talking too Much thumbs I'm talking too much thanks Shirley Thanks Ryan thanks AJ thanks It was a trap the question was a trap There's no way yeah timing is everything Yeah So Okay awesome I know some people may Still be away but I'm gonna talk really Slow and get back into it okay so we've Talked about uh the difference between a Function label a function definition uh Invoking a function versus storing its Definition in a new label now let's talk About what closure is when our function Gets called to I think it was Cam's Point earlier Um when our function gets called and It's finished it's garbage collected the Local memory from that function is Garbage collected it's scooped away it's Taken away and we don't have access to It anymore What if we could What if we could build functions that Memorize things and when we called them Subsequent times they had access to Their previous calls
Right we could build programs that were Incredibly responsive we could build you Know favorites like anytime you interact With any program that allows you to save Favorites or remembers your history Chances are it's memorized it's using Some form of a an encapsulated variable Environment or closure The closure gives our programs so much Power But in order to achieve it in JavaScript The first thing we need to understand is That a function can return a function If you're anything like me my mind was Blown when I first heard that We can build a function And inside of that outer function We can Define another function We Surely you're unmuted sorry it's all Good it's all good and that outer Function can return That newly defined function But remember If we're returning a function like this We're not returning the evaluated result Of that function we're not invoking that Function we're returning the function Definition Let's talk through this Wants to help us Alexander go ahead Talk me through okay yes yes yes uh so Let me get you set up here we have the
Call stack we have the global memory we Have a global Stack frame on the bottom of the stack And we need a toe everyone needs a toe Great Talk me through what JavaScript is going To do what's that first line Okay so in the global memory we are Going to declare a function with the Label create function Uh and the value of that will just be The function definition We will also declare a constant Variable With the label generated funk Equal to Undefined More specifically equal to Equal to the Evaluated result of create function Amazing so once JavaScript hits line six Initializes that variable in global Memory and then sees that it's the Evaluated result of a function what's Going to happen I'm sorry can you ask that question Again of course so once JavaScript hits Line six And initializes this label in global Memory And then sees that it is equal to the Evaluated result of invoking this Function What happens next
Does that create a local execution Context for create function 100 it does Okay does that make sense why yes Because before JavaScript can store what It needs to in this variable We need to figure out what is being Returned by this function And that's because there are parentheses There correct Desperately done okay great so we've Opened up this local execution context Before we dive into the function itself There are a couple other things that Need to happen for JavaScript keep track Of what's going on do you remember what Those are So we need to pop on the Create function frame onto the call Stack and we need to weave our thread of Execution from the global execution Context into the local execution context 100 do we want to pop on or do we want To we need to push Push the Frame onto the call Sac 100 correct yes Okay great so we've moved our thread of Execution into this local execution Context we've pushed a call frame onto The call stack now tell me what's Happening So we don't have any Parameters to Declare in the local memory But within the local execution context
We have to push Another local execution context I don't Know if it's the same Phrase is it it's another local Execution context no I know this is a Trick I'm tricking up to me so are we Actually invoking a function online too We are initializing the function okay so In the local memory we're initializing The function labeled multiplied by two Yes And setting it equal to And setting it equal to the Function definition 100 correct Yep then what happens Okay and then from there the thread of Execution weaves into A new local execution context Does it am I jumping the gun here tell Me tell me why you think that is Well does numb get declared in this Local memory or in the next local memory So let's talk through like where we're At right so we are technically in the Code we're here Right we've entered the execution Context for this create function So now we're weaving our way through Here All that's happening here just like you Said is in our local memory we're Storing the function definition in this New label multiplied by two So inside of this function which
Remembers what we're invoking right here We have now accounted for all of this Information Got it okay where are we now So now we are in the local execution Context and returning the function Definition of multiply by 2 into the Global Memory Into what label Into the create function Result or intergenerated function label Yes 100 so let me change my color back Sorry yes yes yes awesome job yes so we Are returning right this function Definition Just like you said the function Definition of multiply by two Into generated Funk so what is stored in Generated Funk right now The function definition of multiply by Two yep 100 correct so now now that We've returned out of this function We're exiting this local execution Context there are three things that Happen what are they Now we need to Pop off the create function frame from The call stack the local execution Context Is eligible for garbage collection And then we Find ourselves again and we we weave the Thread of execution back into the global
Execution context awesome awesome Awesome awesome Job yes 100 correct Alexander okay so we Just wrapped up line six what happens Next Now in the global memory we declare A new constant with the label result and We set that equal to the evaluated Result of generated funk Awesome Passing in what as an argument Passing in the number three as an Argument fantastic what is currently Stored In the label generated func So the label generated Funk is currently Storing the value of the function Multiplied by two so would we just write That results is The evaluated result of multiply by 2 Passing in the parameter three Yeah but so specifically generated Funk Is a function definition right that's What's stored there and on line seven Because we're passing in three we have These parentheses wrapped around our Argument What happens when we invoke a function So we need to open a new local execution Context we need to push a New frame onto the call stack for Generated Funk yep and we need to weave The threat of execution back into the Local execution context
Yes we do okay so now talk me through What's happening Okay so here We are now We have to Okay I'm searching for the words okay So we have to Initialize num To equal three uh-huh In the local memory And then in the local execution context We are returning The evaluated result of 3 times 2 or Returning six From the local execution context To Result in the global memory And by doing so the local execution Context is eligible for garbage Collection we can pop off the generated Function off of the call stack and we Weave the threat of execution from the Local execution context back out to the Global execution context yes yes yes yes Yes Awesome awesome stuff yes great work Fantastic so what you've just seen is a Function right a create function outer Function define Multiply by 2 inside of itself And return the function definition so Even though this local execution context Is closed Right and we're not calling create
Function again We have stored this data that should Only exist in a local execution context We've stored it under a new label And we're able to call on it later Does everyone see that does everyone Understand that Any questions on this idea of a function Returning a function will go ahead bud So I just have a quick question if if we Um Made a argument for Generate function Like if that parameter held something Huh uh like if we may generate function Holding the parameter num and then we Did uh cost a cost generated Funk equals Create function in taking num and then Const result equals generated funk Three like the number would be three Would it then like would generate Function take pass in the number three Which would pass in to multiply by two Being three like would it return the Same result Is this only working because generate Function is taking in an empty parameter No so if we pass you're saying if we Passed in an argument so like if our Create function took Um let's say our create function took Num and then uh outside of this function Definition we also wanted to like Console log num Is that what you're saying like
Um we could pass in an argument here yes That is what you're talking about is a Closure Uh you're you're basically building JavaScript three slides too early which I commend you on but yeah we can Absolutely pass in A variable Into this outer function And I'll show you in a little bit how That would work but yes your mind is Absolutely in the right place Okay yeah yeah Not to get into sport mode territory but I promise we'll talk about it well cam What's up All right so when we um for example Initialize function multiply by two uh And so when we initialize the function Label in the definition in local memory Or where are the parameters stored is That also like is that attached to the The definition we're storing in memory Is it somehow something with scoping how Does that work it is a hundred percent Attached to the definition so you can Think of the JavaScript interpreter as Seeing this keyword function and saying Okay whatever next chunk of characters Follows this is the label And then anything inside of these Parentheses are parameters that need to Be stored with the definition and Anything in between curly braces is the
Actual definition of the function that Is what's happening under the hood so Those parentheses couple the keyword Function is javascript's way of keeping Those parameters tied to the function Definition yes Okay thank you thank you great question AJ what's up What's up Um yeah uh so kind of I guess it's kind Of like a larger question Um so I don't know you might answer this Later in in the workshop but Um so I understand obviously we're Creating a label which stores the value Of an invoke function you know our last Line is generated fund three if this was Generated funk Two it would be four correct Um so I think where I kind of start not Really getting confused but I start kind Of like asking questions is like are we Kind of getting close to like Dry territory Um Like I I don't know like because when I Hit a closure problem where like I want To store data I start thinking of like Objects Um so I just don't know When when to use this and and in my Opinion I thought everything's an object So why not just go to object but I don't Really know like when to go for closure
Versus Objects yeah yeah yeah no that's a solid Question and the answer is not very Sexy is the wrong word but like it's a Lot simpler than than or it sounds a lot Simpler than it actually is but the Answer AJ is persistence Like if we have an object declared in a Function Right where is it declared is it Declared globally or locally It was declared in the function it's Locally correct so after that function Is done running what happens to that Object what happens to that data yeah We're out we're garbage collected Correct got it so Closure is all about building things Where we can have memory closely tied to Functionality and I'll show you in the Actual closure example towards the end Of this slide deck where you could put An object inside of this closure concept And that object persists so like each Subsequent call of this inner function Could have access to that object which Is really powerful Oh awesome thank you yeah of course but To your previous concern too about Dryness yeah it may not look the most Dry but this concept of returning a Function and storing it somewhere else Is the only way to achieve closure Gotcha cool solid okay awesome work you
All oh Hannah yes talk to me This is a bit of a silly question Um So like I know what the function definition is So generative function is the function Label right Is that like the The name for it Is there like a fancy name or anything Uh it's I call it the function label Some people will call it you know a Variable some people will call it a Constant because it's declared with a Const keyword Um as long as you understand that this Is essentially a placeholder in global Memory for the evaluated result of Creation create Funk you'll be okay That's all this is is a placeholder All right thank you which doesn't really Answer your question it just adds Another word to the long list of things That we could call it so I'm sorry but I've I've only ever heard them called Labels So that's what happens All right thank you yeah for sure okay So this idea of a function An outer function defining a new Function in its definition and then Returning that function definition is Paramount to closure Thank you
Something that We could also do right is we could Define that function inside of an outer Function and then actually call That newly defined function inside the Local execution context of our outer Function let's see what happens if we do This who wants to talk me through it Having so much fun you all are killing It someone throw up a hand come on Cam go ahead bud All right Um so from the top we already kind of Labeled our things we can draw a little Line for the toe if we want yeah It's going to give you some lines glove Numbers thank you Sorry six Uh that would be seven I guess we'll Call nine okay so you said so yes let's Get a line going awesome love it um Sorry You're good go ahead and start us out What's happening in this first line Okay So we've shown Global on the call stack So on the first line we are going to be Declaring a function label outer and Vocal memory Um which its value is just its its Function definition so the F box Excellent Um and the next thing we do is Skip all The way down to nine Where we will be firing invoking the
Outer function yes all right so our Thread of execution is going to take us Into a new execution context that's Going to I can do this it's going to push A new frame onto our call stack yes I'm making mistake for a reason I'm Sorry okay Um so we'll call this new frame outer Okay what happens next So now that we are entering our local uh Execution context we're going to Initialize any variables Um no parameters but we do next have Online to the variable counter that we Will Establish with the label counter Assigned to the value of zero or we go Too much further I'm sorry to interrupt You I hate to be a stickler what uh There's one more thing that happens Before we actually enter the local Execution context JavaScript needs to Know where it is where do we move our Toe oh sorry we take the toe into the Local execution context of outer You're good I'm such a stickler for it Okay you're absolutely right there are No parameters nothing uh no arguments Need to be stored in local memory so We're online two talk me through it We're on line two we are initializing The variable uh counter the label Counter assigned to the value zero where
In in local memory of outer's execution Context uh-huh Right Next on line three we will then declare The function label increment counter in The local memory of this execution Context which has its own function Definition with the the F box Yep After that The code will be invoking increment Oh it's invoking not returning it'll be Invoking increment counter yeah what Does that mean What does that mean so it's going to Spin up another execution context for us So we're going to add another frame Under our call stack for increment Counter s yes yes our stickler our toe Is going to dip into the Waters of Interim encounter as well Um Ah All right And similarly we're going to establish Our memory variables so checking Um nothing new is established in this Scope so Nothing happens on that front the Execution thread then goes to line four Where we will increment the variable Counter which is in the the outer memory Of this up by one yes so let's talk About what's actually happening on this
Line because this is a little finicky And this is where closure starts to Happen Counter right we're looking which we see This keyword counter on line four Where is the first place that JavaScript Is going to check for this word counter I believe it checks the local context of This function increment counter first You're 100 correct so it'll look here And it won't see it where will it check Next it'll then step one I guess layer Out so it'll be the local memory of the The parent function outer Or maybe I didn't use the word parent There but you know what I mean you're I Think parent is totally valid and what Will it find something called counter There it finds the variable counter that We instantiated a while ago and what is Stored in that label counter right now The you know the number zero correct so If we pass the number zero down one Level into this local execution context Of increment counter counter plus plus Our increment uh operator we'll turn That zero into Hopefully a one If everything goes according everything Goes right yeah Great and then a bit of a trick question What happens next So the function is completed we're Stepping out we're popping it off the
Call stack thread of execution or I'll Slow down I don't know you're good sort Of execution leaves back into that outer Uh local execution context of outer Um and we've also flagged that increment Counter function as eligible for garbage Day Um Garbage collection uh And now we are back in The execution context here We're going to do the same thing we're Now ready to step out of outer so it's Going to get popped off our stack Execution context goes back her thread Goes back to the global execution Context and outer also gets Flag is eligible for garbage collection And our program stops and it stops Awesome yes 100 correct nothing is being Returned nothing's being console logged Awesome awesome job cam yes yes yes yes Yes yes So the lesson here is when we invoke a Function Inside of an outer function where it is Defined This local execution context Has access To all the memory inside of itself and As cam so aptly named inside of its Parent function And inside of the global namespace So even though counter doesn't exist
Inside of this function We have access to it Jesus I look like a Psychotic person drawing like this even Though increment counter doesn't have an Argument counter it doesn't have a Variable defined inside of it of counter It has access to the execution context Outside of itself Because this variable and this function Definition Exists inside of the same local Execution context Any questions We're getting to the meat and potatoes Now Alexandra go ahead Did you mention that it also has access To the global memory it does yes so if We had online let's say 0.5 right if we Said const Counter Is equal to 10 We would have counter here Equal to 10. The way the hierarchy goes of things is Javascript will always check like Cam Said execution contexts in order of Ascension Hence the call stack being important it Will check execution contexts going down The call stack If we had counter is 10 in the global Our result would still be the same However if we removed line two and had Counter as 10 our new result would be
11. 100 correct AJ what's up I'm pretty sure I understand the Functionality of I guess access to the Parents Um memories uh but I just want to Confirm kind of the logic it's not Um it's only uni unidirectional it's not Bi-directional I guess if there's other I guess uh nested functions Uh they can't go in like a one nested Function can't go into the memory of Another one it's only it only goes up it Only trickles I guess trickles up yeah Correct yeah if we had another function Defined here with uh another variable it Wouldn't it it that yeah that's my brain Hurts thinking about it yes so if we had Multiple calls and they existed in Execution contexts next to each other But they shared the same parent yes Memory here is not shared it is Individual right okay cool thank you That's correct Great question Uh someone else had their hand up will What's up [Music] Um So If we were to invoke outer again or yeah If we were to invoke it again would it Then increase the counter to two
What do you think Um I think yes but also I think I think no At the same time because like the local Memory gets Um Garbage Garbage disposal what's the word garbage Collected what what is the word it's Some things to garbage collection it's Eligible for garbage eligible that's one Because it's eligible for garbage Collection right so like it gets Effectively like not erased but like Go get a rest so if you were to uh uh Invoke it again wouldn't it just Do a new instance of it yes you're Absolutely correct okay so it wouldn't Like compound correct if we invoked it Again this counter would be Re-initialized as zero in a new Execution context okay But what you're driving out again will You're killing it is closure there is a Way to write this So that that number persists in memory And we'll talk about it Alexander go ahead I'm sorry if you already Talked about this my brain is just a Little slower with some of this Could you call increment counter outside Of that function What do you think
I want to say yes but because it's Defined in that Local memory Would you have to call outer first So if you're calling it yeah if this Increment counter function if the Definition only exists in this local Memory Do you think we have access to it Outside in global No correct Do you see why Yes I think I'm just trying to figure Out What like what the point of having A function I guess if you always have to call outer And then you have to call increment Counter inside wouldn't there be a way To just do that without having to write Two separate functions Yes but you wouldn't be able to achieve What we're setting out to achieve and I'll show you why Okay keep that in mind I promise it will Hopefully be clearer I promise it will Hopefully be clear What a promise cat hi there hi Um in regards to like um business Architecture do businesses typically Want to keep going inwards into local Execution contexts because of like the Independence of those functions that you Can create from the um
I guess like the parent Um Global like execution context I'm not Sure I understand your question can you Ask it again Yeah so like I guess for the Functionality of having like local Execution contexts and like basically Like going within them if you want to Put another function within them in Businesses do they would they prefer for Like any functionality like updates or Anything like that is it preferred to Keep doing that going inwards into local Execution contexts for independence from Closure it depends on the logic that You're trying to achieve Um if we're trying to achieve some kind Of functionality that it rests on a lot Of other functionality and we don't want That inner functionality to succeed Without the previous steps then of Course it makes sense to scope it this Way but if we have Individual Services That are trying to be carried out Independently of each other then Absolutely nested functions like this And closures like this are probably Excess and unnecessary it just kind of Goes with what you're trying to achieve It's a good question gotcha thank you Yeah for sure okay Alexander is that an old hand or a new Hand You're good okay cool okay
We've talked about relabeling functions We've talked about returning function Definitions from functions and now we've Talked about calling functions inside of Other functions where they're also Defined I'm very excited because we've arrived This is closure We can call a function Outside of the function call in which it Was defined By returning its definition into a new Label So all these steps that we've talked About are all coming to a head And I know you may not know what to do Or what to expect but I urge someone who Hasn't hasn't spoken yet tonight to try To communicate us through this would Anyone like to take a stab at it I'm Right here I'm going to help you do it Lane let's do it So all right let me set you up with some Line numbers so that I don't make this Unbearably impossible give me one second One two three four five six seven we'll Call this nine ten eleven okay Lane Whatever well now it's gonna bother me That you didn't put an eight in there so There's an empty line in there okay And I appreciate it okay whenever you're Ready All right uh so we're gonna start in the Global memory over here in which we have
A function definition powder So we're storing that function Definition in the label of outer in the Global memory I love it yes And then we are forgetting about Everything else and just going down to Line nine yes Uh which is a constant variable my new Function And where are we storing that That is being stored in the global Memory Yes and what's being stored there Uh the evaluated result of calling the Function outer Talk to me what happens when we hit that Evaluated result call As soon as we get to there now we are Going to open our new local execution Context Absolutely we are going to push that Onto the call stack expert And the thread of execution also like Weaves into there I forgot about the toe Thank you Yes okay I'm with you All right now we are going to go inside Of that code block for outer in which we Have a variable called counter Which is assigned the value of zero and That's stored in the local memory Excellent yes counter is zero okay Next we have another function definition Called increment counter hmm
So in the local memory that's just Stored as the function Definition Great increment counter and there's a Function definition okay And then the Next thing we have is to return to Increment counter Great So what are we returning Um I'm gonna guess we're returning the Whatever the evaluative result of income Encounter is Or no wait yeah There's no parentheses there so we're Returning the function The function what Increment counter But specifically the function what of Increment counter oh the function Definition So we are returning the function Definition of increment counter and We're putting it where We are returning that to the global Memory Huh Under one label tell me uh under the my New function label 100 correct so now Inside of my new funk is the function Definition of increment counter Talk to me what happens next All right uh so then I'm moving on to Line 10 which is in which we
Invoke my new function I hate to I hate to be a stickler I hate to be a stickler we we gotta we Gotta garbage collect all the things Yeah yeah yeah three steps always three Steps what are they usually yeah we're Gonna garbage collect our local Execution context and book memory we're Going to pop that off of the call stack And then the right of execution goes Back into our Global execution context Thank you so much for putting up with my Harangu line 10 when you're ready Okay now we are going to line 10 in Which we are invoking my new function So since we're invoking my new function We are going to open up a new Uh local execution context in local Memory Push that onto the call stack And wave the thread of execution into This new little area down here Yes So since my new function is assigned the Function definition of increment counter That is what we're going with so we're Just incrementing counter by one Yes and what is counter Counter Was zero so now it is one Okay So we'll say counter plus plus means Counter is one where is counter right Now
Well counters In the uh Other local memory Oh okay I'll say right now you're right Counter is one let's keep going and Think about that while we keep moving Okay yeah yeah I can't remember where It's supposed to go but it exists out There somewhere it's all good yeah yeah So tell me now that We've Ended We've Ended this function right because we've Hit line four inside of increment Counter what happens to this local Execution context now this one uh gets Garbage collected and is popped off the Call stack And our threat of execution goes back to The global education context absolutely And then we hit line 11. 911 as we are evoking my new function Again yeah so we're going to need our New Local memory and local execution context Wow Which will also be pushed on top of the Call stack uh-huh sorry I'm trying to Arrange things make it a little more Legible Damn okay I'm with you yeah part of Execution goes down to this new Call for my function Uh-huh And then we go into our function uh code Block and we increment counter
By one But somehow the counter is already one So now it's going to be two Yeah I just did counter hashtag I don't know Why Okay counter you're saying is two Yep why Um just as JavaScript knows uh you know There's probably some better reason for That but just Totally fair okay let's finish the Program and then we'll talk about it so We've now made counter two what happens Next Uh now that that is done we are going to Garbage collect that local execution Context and local memory Uh pop it off a call stack And Foreign Counter is going that's okay third thing That happens after we finish a function Execution part of execution goes back to The global education context yeah and Then our program ends right Yep where the hell is counter going Let's talk about it so when did we laugh Like when did we first see counter where Is counter initialized that's the word Oh so is is counter now going into our Function for outer So each So initialized in that
That local memory for the first time That we went through outer No that's not where counter is being Stored currently but it is where counter Is initialized you're right oh you know What there's some weird word for this Right that I learned in CS prep is this The uh Closed over uh variable environment yes Yes it is yes yes yes but so counter is Initialized in this local memory of the Outer function right But then the outer function is garbage Collected So when does this When is this moved somewhere else where It could persist and the answer is This line Line knife When I'm going to go back to this Just because it's cleaner in my Handwriting's atrocious when we assign A function definition because that's What's happening here right when we Assign a function definition To a new label Anything That exists in the local execution Context where that function definition Is established Anything that exists in that local Execution context Comes
Piggybacked Onto that function definition So when we assign online nine The evaluated result of outer into the My new function label Outer returns a function definition That returned function definition Has on its back The variable counter And when we invoke My new function on line 10 and 11. What function are we actually invoking Can anybody tell us Because remember my new function is a New label For a different function Alex G Oh we're actually invoking increment Counter 100 correct we are invoking Increment counter So Lane is absolutely right on line 10 Increment counter Counter becomes one Specifically the counter that exists In the backpack of my new function And when we invoke it again on line 11 Counter becomes two Because counter Persists AJ I think I think this kind of answers My confusion with uh oop and closure um Because I think we start talking about
Protos and prototypes and I'm like okay It has access but I mean if we're Creating another instance of the Function then I think that definitely Makes a bit more sense because I was Like okay well it has access but this Definitely uh this definitely helped out Man I I appreciate it of course you are 100 right nail right on the head this is What allows for us to build classes And for us to have individual instances Of classes that aren't affecting each Other you're 100 correct Alexander What's up I think that AJ might have just asked That I was going to ask if Other objects other properties other Other code is in function outer all of That comes along and can be manipulated With each Invocation of my new function If that was to be what it was Manipulating Yes that's correct that addendum is very Important if increment counter didn't do Anything to counter It wouldn't it wouldn't need it right it Wouldn't do anything about it nothing Would change our program Yes 100 thank you Lane what's up Okay so then just curious what happens If You know forget this is my new function
So what happens if we just call outer Again That's a really good question what Happens You know I I feel that there is A chance that counter is still zero Hold on to that question I have Something That's a great question will Um Okay so maybe I'm getting a little bit Ahead of myself here but let's say Hypothetically so outer the function Outer Stores inside of it another function Increment counter what if there was like Another function inside of increment Counter called I don't know who cares What it's called When you then when my new function is Equal to Outer would it then be Still like technically be equal to like The evaluated result of increment Counter or would it be equal to the Evaluated result of the function inside Of increment counter great question so Really what's Happening Here on line Nine right is we're storing the Evaluated result of outer so even if we Had another function inside of increment Counter and we had another function Inside of that function The the thing that's being stored here Is whatever's returned
By outer In this case it will always be the Function definition of increment counter Evaluated result of outer Correct okay yeah that's where I kind of Get confused hey yeah so again the Evaluated result we know that's what it Is because we have these parentheses We're invoking the function the Evaluated result of outer is the Function definition of increment counter Gotcha That makes one more sense that was when I was first trying to like before I Watched this when I was first trying to Get uh or before before I was in this Thing right now I was trying to get a Hold of it that was like so confusing to Me I was like we're calling outer but We're actually calling increment counter Like what is that yeah yeah that makes a Lot more sense no great call out just to Reiterate the spot on the evaluated Result of outer is the definition of Increment counter and we're only ever Calling increment counter when we put Those parentheses on the end of these my New function calls Great call out Okay This is closure y'all we just saw it we Just saw it happen These two lines Proved that our data can persist
So if we're writing this program as the Team and we have these 10 lines in our Code and then will comes in and crushes It one day and writes 10 000 lines After this And then I say oh crap I need to call my New function one more time at the end of Those 10 000 lines on line Ten Thousand And One If I call my new function again The result will be three Our data will persist no matter how much Noise happens in between Okay This is what we're talking about This bond that happens underneath the Hood When we store A function definition in a new label And when that function definition Comes from an outer function where Variables are also defined those Variables come along bonded to the Function definition This bond is called a backpack That's what we call it It is a way for our functions to hold on To information All this information on this slide we've Already talked to talked through excuse Me So I'm going to skip this slide for now But again you will get these slides this Is a revamp of everything that we just
Talked through this backpack Has special names I think Lane mentioned one earlier I think Lane said closed over variable Environment The super Flex Super Saiyan name for This is the persistent lexical scope Referenced data which you will never Hear anyone With a soul say but you can absolutely Flex and say it in your next uh Your next Um Icebreaker question The informal term is called a backpack a Slightly more formal term is a closure Closure didn't really make sense to me Until in my brain I changed the word Closure from closure to enclosure we're In closing these variables alongside the Function definition they are one If you see this in practice in an actual Computer program running in the browser You can open up the properties of a Function definition and you'll see these Closures happen in something called the Bracket bracket scope it is the scope of That function and in that scope Are these environment variables that Persist That's closure y'all But Someone had a question earlier I think It was lame What happens if we call outer again
Here we go here we're doing it we call Outer once and we know counter here is One counter here's two we just talked Through that code What happens if we call outer again Does anyone want to wager I guess what These two will give us Out Um because we're invoking outer as a Function again we're basically passing The scoped variable or the backpack to The new label again so we're basically Starting over And we're starting to cycle over Essentially so now another function as a Label once again is equal to the Function definition increment counter Excuse me but with uh counter Now set Back to zero apologize everyone so the Answer another function when you invoke That the next two times should be one And two again Because of the closure variable how it Resets itself Spot on excellent technical Communication Alex yes you're 100 Correct because we are re-initializing Counter in this invocation of outer we Are setting up a new backpack a new Closed over A variable environment a new closure in This another function If after these two another function Calls
We called my new function again What would my new function be This third time I see your fingers up Ryan I'm calling On you because you're absolutely right It would be free And it would have nothing to do with These being one and two We could call it again it would be four Then we could call another function Again and it would be three these are Independent closures even though they're Coming from the same function definition That is what happens if we call outer Again This is closure y'all Why Why do we do this why is this important Um It gives our functions memory And those memories persist so I use this Example earlier on but it is my favorite Real world example anytime you're Playing a video game and you've done Something and the game needs to remember That you did it I bet nine times out of ten that game is Running the same function over and over Again but it's checking a variable in This closed over variable environment And if that variable is marked as true Then you've already done it and it Probably returns out of that function And you don't get to have that dialogue
Chat with that NPC because you've Already done it It is a way for our programs to remember When they've been run last what the Evaluated result of their last run was That's a memo wise pattern it's very Very very popular It allows us to build iterators Generators it allows us to use the Module pattern I.E I'm building this Program and I want to export it to this Other program while all those variables In that program that your program needs To run inside of that new parent go Along with it It also allows for us to run Asynchronous JavaScript if you don't Know what that is it's all good if you Don't know what anything that anyone has Said tonight is you're right where you Need to be it is okay Every developer started by console Logging hello world never forget that Okay That's it for tonight y'all what's next Keep coming come back more yes I will Have time for questions I promise I'm Not just gonna duck out but keep coming To more of these things Um I'm going to start doing more of These I would love to see you all again Please come hang out Pop into pair programming sessions there Are Community pair programming sessions
Please do those they are amazing utilize CSX it is a free free free resource it Is awesome and yes I have Fast Track codes for you Here they are Again no need to write anything down if You don't want to you can absolutely Screen grab right now if you prefer but You'll also be sent these slides These Fast Track application codes will Get your foot into the door of the Software engineering immersive if that's What you'd like to do You just need to be sure to apply by the End of the date tomorrow Okay I am here I'm happy to answer any more questions You may have I'm happy to talk about Anything you'd like to talk about the Program closure uh what I'm watching on TV which is nothing Um But if you needed to go it has been an Absolute pleasure seeing you having you Here thank you for your energy and Attention and if you want to hang out And ask some questions I'm here cam What's up Uh all right I've got a a few questions Um they get increasingly complex uh First one is is a is a function That we've created uh you with a closure Uh attached to it is that an example of
A I think it's a pure function is the Term I saw in other materials so it's Like it's not like since that variable Is local too it's not interfering with Anything else is that an appropriate use Of that term That's a really great question I'm not 100 sure I think it would depend on a Few factors I would argue that Closure is not a pure function just Because I know a pure function is Specifically not creating any side Effects And there are a lot of side effects that Come with closure Um I don't know a hundred percent though I think it would depend on what kind of Functionality You're Building into that Closure okay that makes sense to me Um next is is the backpack the closure Is that like straight is that like Distinctly part of the local memory of The new function or is it like adjacent Or attached uh in linked via the scope Property Or is it something totally different I think it's both I think what you're Saying I think both the things you're Saying are correct so like when when we Return this definition of increment Counter I'll call it IC yeah on that on That definition here right is a little Backpack in the form of the scope Variable right the scope property excuse
Me So that exists local to this function And also in global memory because it's Stored in This Global variable Sure but but it's is it's still fair for Me to say like it also exists in like It's part of the local memory of of Increment counter I think it would be safer to say that It's a property local property okay Yeah a property on the definition for Increment counter okay that's clear Um then I have one more this one's a Little more Uh a tricky so I hope I get it right on The first try so when you Um have closures for multiple functions That were created in the same execution Context so if we were Returning more than just increment Counter with an outer Um CSX when I was reading it it said That they will access the same variables In memory but I thought that the Variables lived like in the backpack of These individual functions so is there Like some sort of how is that being Linked like how is if counter was still Discounted we had multiple functions Inside outer how do they all hold on to Counter Um and treat it as the same thing Does that make sense that question I Think so let me play it back to you you
Tell me so you're saying if we have a Counter here and then let's say we have Another function in here and we'll call It decrement right decrement counter So Conditionally okay we return either Increment counter or decrement depending On whatever right Both of these function definitions will Have access to the environment variable Of counter when their definition is Returned out of this parent function However It will not be the same counter so if You and I passed if if we run this Function twice if we run out or twice And we return increment counter one time And decrement counter the next each of Their backpacks contain an independent Counter initialized at zero And if we call increment if we call Let's say my new function stores Increment and another function stores Decrement this will result in one this Will result in two If we're decrementing by one decrement Will result in negative one negative two These two counters are separate of each Other even though they're coming from The same function does that make sense That makes sense If they were the same like this is not What's happening but if they were the Same this first decrement call would be
One right because two minus one is one But they're not the same they're Individual okay and sorry to keep Pushing on this topic but how would we Create a situation where decrement and Increment refer to the same backpack Guys thing or is that like how would we How would that happen what you just Showed me yeah so this is where um I Don't know if AJ is still here if they Left but this is where something like Using an object would come into place Um like if we had an object stored in This counter variable like if we said Const counter is equal to an object Where we have like a true Count and a False count Right or we could just have counter in There Then I would as a developer say instead Of calling this increment counter I Would call this like effect counter or Something And then depending on whatever was Passed into This call We could know that we either need to Increment or decrement it Got it okay that's all clear thanks for Entertaining my tangent of course yeah Just like a little bit of abstraction Allows us to have that power to do two Different things Cool all clear thanks man yeah yeah for
Sure Alex what's up Um I have a quick question just about Es6s syntax Um I know CSX kind of like kind of Reinforces it a lot Um where does that stand in uh industry Best practices because I honestly find It more confusing but I've tried made The habit of writing my inner functions With it like my function parameters with It but like is it used in the industry Yeah it is pretty it is okay Unfortunately pretty extensively I will Say I am 100 in the same boat as you When I first saw this weird thing like I Was like what the hell am I looking at Right like what what what do you mean Arrow function where are the parameters Where's the return statement like There's no return what is happening and Then you'd write const label equals if You were to to name it right but like I I know how that like seems It's supposed To be easier but honestly I find it Almost more confusing in a in a way yes Yeah Um it will become second nature the more You see it and the more you interact With it and I know that's terrible to Hear because it hurts to say That it will and it is really very very Popular in the industry and it gets even Crazier and I don't know why Um one of my colleagues he says this all
The time and I love that he's like we're Paid to write code why would you want to Write less code like you you're paid to Write it why wouldn't you want to write It So there are a lot of people who are the School of thought write it clearly so That when you write an awesome function Alex and I come in the next day and have To review your work or use your work to Build what I'm building it should be Really clear There are some people who aren't in that School of thought and a lot of those People unfortunately are in leadership Positions at companies around the world And they just want things like really Efficient and as few CO as few lines of Code as possible and it's like newer It's also newer there are no performance Games like it has no effect on the Performance of your Algos or your Functions it is literally cosmetic but I Promise you the more you look at it the More you think about it the more you Start to use it it will become much much Easier I was in the exact same boat as You I mean it genuinely I didn't write An arrow function until like three Months into the immersive program Another Internet Explorer has gone you Have to use it more probably yeah all Right yeah Internet Explorer is Deprecated as a whole but yes
Especially with like functional Front-end Frameworks like react now Utilizing Hooks and that becoming the Industry standard like even front-end Engineers are writing front and code in Es6 Arrow functions so it's you're it You're I hate to say you're not going to Escape it but it will just start now Definitely well also just like don't Feel like in a rush to understand all of It because there's a lot and there's a Lot of adjusting that it takes but don't Shy away from it and if you feel Empowered to start writing them start Writing them Um like Should I should I get into the habit of Writing the main function body as that Or is it still best to start the main Function as a keyword function and then Or does that not even matter personal Preference again they're exactly the Same under the hood so whatever makes You feel the most comfortable like if Writing the outer body function is Enough of a challenge like just do that Um but as you get more comfortable with Like native array methods and you want To start writing reduce callbacks as Arrow functions and it looks freaking Crazy it looks like some kind of weird Or sometimes impossible to understand Stuff go for it but until then write it When you can read a lot of it when you
Can and just know that it will take Effect it's like you if you go into a Job interview tomorrow and you don't use Arrow functions you're not going to not Get the job because of that like you're Not you can you can write your function Definitions and you're fine it's just Something to get used to because a lot Of developers use it and you're going to Be reading a lot of code as the Developer The methods are the only ones that I I Only know how to do them with the arrow Function so but anyway that's all Solid yes yes yes Alexander what's up All right I'm a little I'm a little I am a little bit confused By the fact that outer is returning the Function definition each time So when you're calling The function To me Or when you're calling outer to me it Would return the same thing every single Time so where does counter actually Increment from if you're not Returning like the evaluated results of The function like it to me it would just Be returning the definition returning The definition returning the definition Why does it change The short answer is because we're Redefining the function every time This is why defining the function inside
Of a function is Paramount Because Sorry I'm switching slides so much so Because We're defining increment counter Inside of outer Every time just like this just like this Variable right if we got rid of this Function if we got rid of all this stuff And we called outer here and then we Called outer again those two variables Would be independent of each other right We wouldn't have access those cross Execution contexts so with the same Concept in mind We are defining we are storing the Definition of this function inside of a Variable In the local execution context of outer Each time it's called So this definition Exists Only in this execution context until It's returned And then if we call outer again we're Redef like it's a new definition It is uncoupled from this definition Even though the code looks the same Remember it's a reference to the Function the reference is different Sorry is there anything that I can do to Help clarify no I think I just need to Look at it thank you I appreciate it of Course yeah yeah it's a tough this is
This is where closure comes like this is It this is the hurdle Meredith what's up Hey so I don't have a question about Closure but I do have a question about Pair programming if that's all right Um I I feel like I'm getting ready to Start pair programming soon and I'm Curious when you're new to that do People like work through CSX together or Are there other challenges you use like What are the materials for pair Programming that's a great question CSX Is a great source of material when so Yes 100 and I think there is a CSX slack Channel that you can join if you're not Already a member There are always messages hey I'm around Can anyone pair for a couple hours and You dive into program or challenges Excuse me CSX yes there's also Excuse me A repository of a bunch of pair Programming questions and algorithms That are made available to you when you Come to one of those code Smith Community pair programming sessions Gotcha welcome to those sessions because Those questions are then yours in Perpetuity and you can use those anytime You want a pair program Yeah okay cool thanks great question Anyone else Erica what's up
Hi Um I have a quick question about if it's Possible Using To access I guess the value of counter With the variable label my new function Or if you would need to return the value Of counter within the definition of Increment counter if that makes sense Yeah we would have to write we would Have to make some changes to the code It's possible right now as this code is Written not so much but yes if we Returned or console log counter inside Of the increment counter definition then We would have access to it here yes okay Great thank you yeah great call out will What's up Okay so I have a question that's Um unrelated to what we're talking about Directly in here but it has to do with Closure Um it's a concept that's addressed in One of the CSX problems am I allowed to Like share my screen is that okay also If you'd like tell me what question it Is because I can pull it up and I can Play myself uh it'll be a challenge After In uh closure and scope so my question Is So we're creating a constant which is Going to be called called and that is Equal to
Um A function that takes in a string and Returns hello plus that string and we're Creating another constant called after Called which is equal to the function That we created taking in three and the Function called so when we when we log It in console.log with Um with world and it eventually Uh to prints Out World or hello world Because of how it runs whatever [Music] We call after called And then we put Um as an argument inside of after called The string world After college is equal to after so is it Basically just it already knows like we Already know what is going into after so We add world and that just like Transfers down into our function cycler Argument So this is a great question Specifically world this argument is Taking the place of this parameter That's what I thought but I'm just kind Of wondering Like if there was another Function inside of cycler could we put World comma another argument and then That would be like okay that one's going To go down to the next one Yeah yeah you can I mean this the way it Makes sense but if if you wrote that
Differently if you just wrote like Instead of like dot R just wrote like Uh string or whatever Yeah we can actually do it right now Because I've written uh let me see I Think this should work No it doesn't what am I doing three After callback oh because the Callback Is only expecting one string yeah but if You were to write like um another one if You were to change dot arcs to just like A one argument and then make another Function inside of it and make it one Argument And you made you know you did World Comma High I don't know would it then like it Would take in world for the argument for Cycler it would have taken high as the Argument for the function inside of Cycler is that kind of how it works Yeah so I think To achieve what you're saying we would Need to change the parameters like I Just did in the Callback function which Is this called function right this is The Callback so I I've written cycler This way to account for multiple Arguments being passed into the new Label that's what's happening here right This is the new label if we pass in more Than one argument into this new label Our inner function is accounting for Those
The Callback is not So by adding this it's called a rest Parameter if you don't know what that is I highly recommend you look it up super Powerful this rest parameter allows for Multiple arguments being passed to this Callback function Thus giving us this result like we can Put in 600 like I can copy and paste This all day Well I'm going to need commas But if I do this It doesn't matter how many arguments I Have it will work It'll just keep Adding them on correct I see So then how would you If there was another function inside of Cycler that took in another parameter How would you then Um In the console log after called how Would you then give That like how would you then input that Parameter sure well it depends right if We have a function definition inside of Cycler and let's call it cycle two And it takes a number argument right and It does let's say console.log that Number that's all it does if we ever Call this function right like if we call On the next line if we say cycle two We can pass in whatever we want as the
Num And it can be Like like you're saying if we add number As the second argument there that's in Our scope And we can invoke cycle two passing in That number from cycler and then We would have to specify That the second argument that we pass in Here Is a number Okay and then every argument after it Could be whatever we want I see that makes sense it it does Um But what doesn't make sense I guess is Because the first argument in cycler is An argument that takes in multiple Arguments yeah why would the three not Be counted as one of those arguments That's being taken in you're 100 correct It would actually need to be the last One But even then why would it not count as One of the many because because it's a Different Because it's not a string it's a it's an Integer or a number yeah has nothing to Do with type ironically has to do with Placement in our argument list so Because in the function definition of Cycler we've said hey we're going to Have a whole bunch of arguments or maybe One they're going to be strings maybe I
Don't know what they are but all of These arguments uh rest these together Rest these parameters together and then The last one specifically the last one I'm going to refer to as number in this Function So like that specific one pull out and Hold remember in local memory as number This is why the order of your arguments Matters right like if even so let's say I got rid of this rest parameter And I put name Date ARG and number If I wanted to invoke this function Using the arguments Uh Sam today Uh no and 10. If I passed in 10 and no Even though 10 is a number JavaScript Goes oh 10 is ARG right now Because that's the order that these Arguments are passed in has nothing with The actual name of the argument it has To do with their location in the Definition It doesn't make sense but it I'm still Confused like it makes sense in this way Well with the the resting argument what Would you call it Um I still don't understand why it like How it differentiates Is a big
Is it because it's the last one in the Order it knows this one is going to be Different than Uh that other group like it's just Because it's the last one so if you were To Take it out or if you were to take it Out and make Sam the last one it would Say number it would be Sam correct okay That makes sense I thought it was just Like an infinite thing it's like oh yeah It's gonna take in all of these Arguments as well yeah I got you place It at the end it'll count as the next Argument in the order if you're not Familiar with it what the rest parameter Is actually doing is it's taking all the Arguments and putting them into an array So it's taking this indefinite amount of Arguments and arrayifying them and by Specifying that we want the last Argument to be a number JavaScript will Basically go okay Everything in this argument list is um Is a is is needs to be moved into an Array oh except for the last thing so Electronic index in one and hold on to That last thing I got it and then it would take that Last thing it would put it into or I Guess you would change it to num and Cycler and it would take that and then It would we would call it in our Function cycle two and then it would
Take that number and put it Correct Would you even need to put a parameter In cycle two since we already have Called it in this uh in like the parent Function before it if you remove that is Do console log dot num or console.log Num would it still just So we wouldn't be able to do num because Num isn't a number yeah we would do Number yeah and that would print our Three still right that's literally a Closure yeah okay Okay cool Uh would it be bad practice would it Even work if you were to do two rest Um parameters Um next to each other like how would it Know when to differentiate that's a Really good question I suspect that it Wouldn't Okay I figured if nothing else it was Probably bad practice because it seems Like it would be confusing but uh yeah Yeah I also can't really think of an Edge kit like a use case for that like Okay just because of single use Principle like you want a function to do One thing and if you're taking in Multiple lists of data Like they should already be in an array Or a list like form like sure yeah that That hurts my brain yeah yeah I was just Curious oh that's great
Um I guess a slight other question would You ever see like backpacks within Backpacks Using closure or is that just not not Something that generally happens uh yeah Of course I mean yeah you can absolutely Do that uh again use case but like I've Seen modules which are in themselves Closures contain functions that also Have closures like yeah for sure okay Cool I'm just curious thanks great Question y'all it's been a pleasure Thank you all so much for hanging out With me thank you for the amazing Engagement awesome questions I hope to See you all at home and technically in Taking technical interviews can't wait To see you all Have a good night everybody