Demystifying JavaScript Closure

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
closer is sometimes seen as one of those mysteries of JavaScript I still remember when I first grasped the idea of closure it was an aha moment for me and since being able to grasp that I've been able to see how much it is used within JavaScript and also I've been able to apply it to solve certain problems so closure is not a new construct it's simply a concept that's used to describe what what's possible within JavaScript and by understanding it it opens up possibilities for you that you may not have thought of in the past and it enables you to understand JavaScript code that is frequently being written out there so let's take a few moments and demystify the whole idea of closure now closure is closely related to scope so I want to define scope briefly as a starting point now we've created a previous video on scope so you may want to visit that to review scope in more detail but basically javascript uses function scope meaning functions determine the scope of items that are declared within that function and school basically refers to the rules that determine where within a pro our program the program we write variables and functions are accessible so I'm going to jump out to sublime and take a look at a simple function actually two functions that I've created both of these functions define scope now first off we have global scope which they are defined in but inside of the functions there is scope as well now function two is defined inside of func and because it's defined inside of funked it has acts to the scope of funkin here's the scope of Fung however from three being defined outside of funk does not have access to the scope of funk and that's easy to see when we simply call funked and funk three display the console first and refresh down below we see a five printed out but then we see a reference there when we called funk 3 because funk 3 tries to access variables that do not exist for it the rules of scope say it cannot access the variables that have been declared inside of this function but when we called funked it called funk - and from - even though it defines its own scope it also has access to its parent scope so it it is able to access those variables now let's define closure I've gathered three definitions of closure that will look at first and then we'll look at several examples first off this comes from JavaScript kit comm a closure is the local variables for a function kept alive after the function has returned so what is saying is when a function is finished those variables are still accessible another definition closure is when a function is able to remember and access its lexical scope even when that function is executing outside X lexical scope now that definition comes from Kyle Simpson he wrote the book scope and closure which is a great book for defining both little and understanding both of those terms and third a closure is a function having access to the parent scope even after the parent function has closed that's from w3c schools so in these definitions it talks about code executing outside of a scope and yet still having access to that scope that's the commonality of those definitions of closure so if we jump back to this example that I was doing funk 2 does have access to the scope but it's executing inside that scope because it's called is very the very last thing so it executes before this function has completely finished so it illustrates scope but perhaps not closure if we were to get really technical about it so let's make a change that will show closure and a great way to do that is with callbacks callbacks are definitely functions that execute outside of the scope so I'm going to enter set timeout and I want it to execute func to after 1 seconds now if you're not familiar with set timeout this is a function that allows you to call an execute code after a certain length of time it takes two parameters the first is the code that will execute usually that is entered as a function normally as an anonymous function in this case we are just calling a function and the second parameter is the number of milliseconds that should wait before it calls that code in this case 1000 milliseconds one second so when we call this it will set up the scope it will set up this function and then it will call set timeout and at the time app right after it call set timeout this function is done it closes it's no longer running however a second later it then calls a function that was part of it and that function right here then has access to these variables because it retains that access to the scope even though it's executing outside of that scope so let's say that open the console and we'll go ahead and refresh and execute it and five appears so we get a pause of a second and then five appears so that first function is already closed it's done it's executed but we then through the set timeout command call back to that function that was defined inside that scope and it still has access to its parent scope and it can add those numbers together so one example of closure so the way we describe this is funked to close us over the scope of funked and continues to have access to it that's where the term closure comes from all right another example I'm gonna go to a different page where I've got two buttons created I'm going to use this as an example this will also use callbacks but we'll use this with an event handler I'm gonna paste in some new code so here we've declared a function counter inside of that we've declared a variable CMT which we're going to use for count simply counting and then we have access the two buttons which are on the page they have an idea of item one and item two so we've grabbed those so that we can add an event listener to them we then then declared a print function and then it simply logs the value of this variable to the console that's all it does to each one of those buttons we've got an event listener and the the function for the code they will execute is count one for the first one and that simply increments the CMT variable and it calls the print function and then count two for the second one it does the exact same thing now when we call this function it will execute and it will complete and it will finish however when we click on the button they will still or buttons they will still have access to this variable and to this function even though that function has finished now one way to show this working would be simply call the counter function at this point but what's commonly done when you have a function set up that you only want to execute once is simply to immediately invoke that so the way I would do that is put parentheses after the function definition now since we're going to immediately invoke that I'd remove assigning it to a variable and just out of convention meaning it's commonly done when you are immediately invoking a function I'll put parentheses around it this is called an immediately invoked function expression but the real concept that we want to convey here is closure that even though this function immediately invokes and finishes function count one and function count two will still have access to the scope that was created by function counter so it will have access to that and it will have access to the print function as well so let's take a look at that save that refresh click on one button and as we can see it increments and prints out a one click on it again increments it again prints out a two so it keeps that variable is keeping track of the value even if I click on a second button which executes an entirely different function it still retains that value in increments of by one because they both have access to the same scope so jumping back and looking at that code again so one way to describe this is that count one has closure over the scope of counter we could say that about count two as well or another way to say it is count two still retains a reference to the scope of counter and we call that closure all right one additional JavaScript pattern that illustrates closure very well is the module pattern now I don't plan to explain modules in a lot of detail I just want to show you a simple module pattern and explain how closure is involved so I'll paste in some new code now what we've done here we've set up a variable and then a variable is equal to an immediately invoked function expression and if e so that simply means that this is going to execute as soon as this page loads now one thing that we've done different is at the end of that function we return something so that variable will now contain the contents of what we have returned now what is it that we're returning well it's some of the things we've defined within this module one is a summit function and one is multiply it function both of these functions we can pass in a value and it will add it to a variable that was defined or that was declared inside the scope of module and it will also call a function that was declared inside the scope of module so these two functions will retain a reference to both of those which we call closure and we can refer to them anytime we want by going app dot summit or app dot multiply it because we return those two functions as part of an object literal so let's say that refresh this and take a look at how that works at the summit let's pass in a five and it prints out an eight let's do app bolt apply it pass in a five again and it looks like I left out part of this function so what I get for hurrying fast so we'll add that back in refresh again whoops pass in five and it returns a 15 so we now have access to both of those functions and we can use them anytime we want and we can use them throughout our code and both of those will always have access to the function print it and I'll have access to the variable a because of closure hopefully that helped you understand closure better hopefully you had a few aha moments those are exciting to get with JavaScript because then you begin to understand things better if this video brought up questions or comments please put them in the comment area and if you found this helpful like the video subscribe to the channel and best of luck in your future JavaScript endeavors
Info
Channel: All Things JavaScript, LLC
Views: 21,701
Rating: 4.9289098 out of 5
Keywords: Javascript tutorial, javascript closure, closure, javascript scope, scope, Javascript for beginners, beginning javascript, javascript fundamentals, javascript programming, Javascript callbacks, javascript callback functions, callbacks, callback functions, Javascript basics, Javascript essentials, module pattern, javascript modules, javascript module pattern, Javascript closures tutorial
Id: TznpOmv2BQM
Channel Id: undefined
Length: 16min 8sec (968 seconds)
Published: Mon Oct 03 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.