Javascript Closure Tutorial | Closures Explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Great video. Nice work.

👍︎︎ 2 👤︎︎ u/TheNerdyDevYT 📅︎︎ Jun 22 2021 🗫︎ replies

In this Javascript Closure Tutorial you will learn the concept of closure through multiple examples. Closures explained in this way may be easier to understand. Closure is often confused with lexical scope which is an important part of closure, but it is not closure itself.

Javascript Closure Tutorial | Closures Explained

✅ Intro

✅ Example 1: Lexical Scope is not Closure / Closure Basics

✅ Example 2: Closure with an IIFE

✅ Example 3: Closure with an IIFE and a parameter

Was this tutorial about Javascript Closures helpful? If so, please share. Let me know your thoughts in the comments.

Javascript Closure Tutorial | Closures Explained: https://youtu.be/1S8SBDhA7HA

👍︎︎ 1 👤︎︎ u/DaveOnEleven 📅︎︎ Jun 20 2021 🗫︎ replies
Captions
hello and welcome hi i'm dave as your javascript knowledge increases closure is a very important concept to understand let's talk about it [Music] it is important to understand scope as we discuss closure and i will link to my tutorial on scope in the description below but first let's start off with defining lexical scope lexical scope defines how variable names are resolved in nested functions and therefore if we have a child function within a parent function the child function has access to the scope of the parent function and has access to the global scope nested child functions have access to the scope of their parent functions but this is often confused with closure but lexical scope is only an important part of closure it is not the entire thing so let's start off with looking at a scope that's the global scope here and we've defined a variable let x equal one and then we're going to create a function i'll name this parent function we'll make it an arrow function and inside the parent function we'll have a local scope that is local to this function and here i'm going to define a variable called my value and set it equal to 2. now the parent function here is a child of the global scope and so it has access to the value of x that will go ahead and log to the console and it also has access to the my value variable that we just defined however the global scope if we were to try to log the value of my value here in the global scope we would get a reference error because it does not have access to the variables defined in the local scope of this parent function so i'll go ahead and save this and if we call the parent function underneath we'll see the results of this and we get a 1 and 2 in the console however this isn't defining nearly as much as we need to yet so let's go ahead and create a child function within the parent function and then this nested function will have access to the global scope so we can say x and add 5 to it with the plus equals and then we can also access the my value variable from the parent function and we can go ahead and add one to that and so this child function has access to the values from its parent function and the global scope and this is lexical scope this is how we're applying the nested child functions having access to the scope of their parent functions and it doesn't just stop at the parent they can go to the global as well so we can go ahead and call the child function inside of the parent function and then when i save we get all of these values returned to the console so our initial 1 and 2 on lines 13 and 14 are 1 and 2 here and then on line 17 and 18 we get 5 added to x so we get 6 and then on line 18 we get 3 because we've added 1 to my value but this does not display closure although we can say the child function has closure over the scope of the parent function because it has access to it and we can even say the child function has closure over the global scope it does not directly give an example of closure it's just lexical scope is an important part of closure it is not actually showing what closure is so we need to change our example to actually display closure a good definition of closure actually comes from the w3schools website and it says a closure is a function having access to the parent scope and again that is lexical scope but it's only an important piece here so a closure is a function having access to the parent scope even after the parent function has closed and that is the key ingredient for giving an example of closure and to further expand on this we can say a closure is created when we define a function not when a function is executed and for an analogy here think of a professional sports game football i'm in america so my football may be different than yours baseball tennis anything that requires a field those boundaries are set before the game is played and that's how you can think about a closure it is created when we define the function or you could say the boundaries are set we're telling child function what it has closure over at the time that it is defined it is defined within the parent function and so that is giving the child function access to not only its local scope but it also has access to the parent function scope and it has access to the global scope so it could be said that it has closure over all three but now we just need to give an example of what it means to have access to a parent scope even after the parent function has closed and this is the key part right here so now let's change this function and we'll give the child function access to these scopes even after the parent function has closed in order to do this instead of calling the child function inside the parent function we actually need to return the child function and we don't want to call the child function so we're actually just returning the child function from the parent function when it is called and so now if we set i'll just call this result if we set result equal to the parent function and then i go ahead and save notice what we get in the console we don't get any result from the child function or what we would expect here on lines 21 and 22. it hasn't been called into action that we just returned the function itself so all we got was what's on line 17 and 18 when the parent function was called into action here but it returns the child function so now we can use result to call the child function and actually to further highlight what i'm saying if i just log what result is you can see it is our child function and since it's an arrow function it's an anonymous function and it was just referred to as child function so we just get the anonymous function here in the console so now we can call the child function as result and it has access to the my value variable even though the parent function has already been called and closed it is already returned and so now when i save and i call result you can see lines 21 and 22 we get 6 and 3 and that means because my value was not defined inside the child function so although the parent function has already returned it is already closed the child function still has access to the scope and that makes my value a private variable that only child function has access to further if we call result again you may be surprised at the result notice it's not 6 and 3 again it's 11 and 4. it continued to increment these values so we incremented my value by another one so now it is 4 and instead of 6 we added another 5 and so now we have 11 and if we call result again it will continue to increment and that is because it is incrementing both of these values and it has access to the global scope which is a public variable but it also has access to the scope of its parent function which is a private variable and to further highlight that if we want to go ahead and log to the console the value of x we can still do that and this we got the last value of x which is 16 but if we try to log to the console the value of my value we should get a reference error because it is a private variable and that's exactly what happens my value can only be accessed from the child function unless we were to call the parent function again which at this point we're not going to because we've already set result equal to that so this is a good way to create a private variable and then only have access to it with a child function so that is closure because we have access to the scope of the parent function even after the parent function has returned let's look at another example i'm going to create an example with an immediately invoked function expression that's iife and you often see closure examples with iifes if you haven't seen one of these before i'll quickly run through what an immediately invoked function expression is here i'll define private counter i'm going to set it equal to an arrow function but i'm going to put that arrow function inside parentheses and then after i have this initial definition inside here i'm going to call it into action immediately by putting the parenthesis parentheses operators right after it and so this will call this function into action immediately and that is an immediately invoked function expression i'm going to set count equal to 0 and then i'm going to log to the console a template literal that says initial value and here i'll put the count value inside this template literal and after that i'm going to return an anonymous function and here i'm going to set the count plus equals so we'll increment it by one and then i'm going to log the value of count and after that i'll go ahead and save the function and we see in the console i have initial value equal to 0. why did that happen because this function was already invoked it's an immediately invoked function expression so now private counter is equal to this function so it's essentially what we did before with the named functions except i didn't have to set result equal to the name of a function we just invoked it immediately and now if we call private counter afterwards we'll see now we have a value of one so count was incremented and then we just logged it to the console and if we do that again and again we'll continue to increment our counter but we're using a private variable to do so this is not available in the global scope the only way that this variable can be accessed is through the the lexical scope of the child function here this anonymous function and so it has closure over the private counter scope and of course it has closure over the global scope however all we'd really need here is having closure over the private counter scope so we can have our private variable that increments the counter it's important to highlight that this console log statement only happens once this original function that is called into action immediately only returns one time and it only returns this function to private counter one time after that when we call private counter we're calling this function and that is why we only see the console log that says initial value in the console one time after that every time we call private counter we get the return value or the console log actually of the count value here so if i were to remove our private counter calls and save once again we just get the initial value console log statement here this function is returned but it is not called into action immediately it is only called into action with the calls to the private counter okay let's look at one more example with an immediately invoked function expression that will give us another example of closure and in this example go ahead and give us a little extra room in this example i'm going to define a function called credits reminds me of when i used to go to the arcade and put money in the games but we want to pass in a parameter and so we're going to need some credits to play an arcade game but we have a limited number of credits and this is an immediately invoked function as well and so at the end we call the operator parentheses to call it into action but we need to pass in oh and i've got a minus and still equals sign there we need to pass in the parameter immediately since this is immediately invoked so let's say we start out with three quarters and so to do that when the function is invoked you pass in the parameter in the operators at the end so we're passing in three credits immediately so here we'll say let credits equal oh that was a minus again equal num and from there we'll log the initial credits value and we'll log the credits i'm going to return an anonymous function and this anonymous function is going to take credits and instead of plus equals one it's going to say minus equals one and subtract a credit for every time we spend a credit and then if the credits are greater than zero we'll log to the console and we can say playing game and we'll include credits in this template literal and we'll say credits remaining and then we'll also have another if statement we'll say credits less than or equal to zero and we can say console log and here we'll just say not enough credits so just an example of how we can actually subtract with the function and if we save this we get our initial credits value of three but we're not subtracting or playing a game yet so we need to call credits for that to happen and we've already passed in our value our starting value of three credits so now when we call credits and save we get plain game two credits are remaining and likewise we can go ahead and copy this line down and now you can see we played a game we had two credits remaining then we played again we had one credit remaining and then when we wanted to play there were not enough credits and here you can see how credits is the private variable that is accessed because this anonymous function that we return from our immediately invoked function this anonymous function has closure over the immediately invoked function that has the private credits variable because this credits variable is private it's not available in the global scope and the only way to access it is through the child function that is an anonymous function here well i hope these examples have helped you understand closure and if you were not previously familiar with lexical scope i hope it has also helped you understand how it is not closure but lexical scope is an important part of closure and after that of course remember in the description i have a link to my tutorial on scope thank you so much for watching and liking supporting sharing all of those things please leave comments below i'm curious if you have questions or if you have another definition that you think nicely sums up closure as well i'll talk to you guys again very soon
Info
Channel: Dave Gray
Views: 3,067
Rating: 5 out of 5
Keywords: javascript closure, javascript closure tutorial, closure tutorial, closure explained, javascript closure explained, closure examples, javascript closure examples, js closure tutorial, js closure explained, js closure, js closure examples, javascript closure interview question, javascript closures in depth, closures, javascript, js closures, javascript closures, examples of closure, closures explained, js, closure, javascript closure example, javascript closure function
Id: 1S8SBDhA7HA
Channel Id: undefined
Length: 17min 58sec (1078 seconds)
Published: Sat May 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.