**If you are confused about his code example, please see my 3 step explanation:** 1. The outerFunction('outside') is called immediately when it is assigned to the variable "newFunction". (That's how it works when a function is assigned to a variable with (), if you didn't know this part, you would very confused). 2. Upon being called, outerFunction returns the function "innerFunction(innerVariable") which re-reassigns our variable "newFunction" to be InnerFunction(innerVariable) instead of outerFunction(outerVariable). 3. Then by calling our variable as newFunction('inside') we are calling innerFunction('inside') which runs the console.log code. The closure is that innerFunction remembers and has access to the outerVariable parameter we originally set with outerFunction('outside'). Thus it is able to console.log both 'outside' and 'inside' even though it was called with just 'inside'. If this helped you please thumbs up so others can see!
SUMMARY: Closure i s "when you have a function defined inside of another function, that inner function has access to the variables and scope of the outer function even if the outer function finishes executing and those variables are no longer accessible outside of that function."
*personal note* newFunction call = (outerFunction + calling it). outerFunction executes, returning innerFunction while passing in "outside" as part of the accessible scope. newFunction then passes "inside" to the now returned innerFunction, calling it and completing the execution. For anyone reading, I have no idea if I'm right but this makes sense to me rn. Analogy note: newFunction is like the first car key turn, it activates the starter (outerFunction) which primes the engine by passing in "outside" and returning innerFunction as ready to ignite. The second turn is newFunction passing in "inside" which sends fuel, igniting the engine (calling innerFunction)
I think I FINALLY understand closures. In fact, I found a good reason to use one today in my project. TLDR; When you need to pass a function with no parameters, but the function you want to pass has parameters. BAM, create a closure by putting the variables/parameters you need in the outer function and return a function with no parameters (just remember that returned function has access to the outer function parameters, even after it's done executing).
Closures are such an interesting topic that I always watch anyone or everyone coming up with an explanation for the same. This was one of the best explanations that I have come across.
Haha okay one tip for you. If you are smart enough you would understand. Javascipt variables do not holds the values they rather holds the references to the physical memory slots in which values are contained. When variables are returned from a function , it forms a closures because the function is not returning the variables/values, the function is rather returning the references to memory slots .. That's it
There's more to it. That's actually lexical scope. Lexical scope comes into play in the concept of Closures when that lexical scope is 'closed' out, hence the term closure. A Closure is when you still have access to a lexical scope that has been closed and the values should have been garbage collected are still available to your closure / function that is still accessing them.
I watched many videos on closures but everybody trying to explain too much and somewhere lose the real thing. Your example and explanation are good. I got the concept. thank you for this video.
Closures allow functions to access variable values, declared in another (parent) function, even after the parent function has finished it's execution. In js, the variables within a function are accessible only within itself and only for as long as the function is executing. You can understand this, by creating a new variable and assigning the parent function to that variable. Then do 'console.dir(new variable). Try below example : const add = function(){ let num = 1; return function() { num++ return num; } } const addFunc = add() console.dir(addFunc) in the console > click on 'f anonymous()' > click on 'scopes' > click on 'closure' In the above example, the addFunc function is declared in the global scope. Hence, it should not be able to access the variable in the add function, because variables can only be accessed within the scope and and while the scope still exists (as long as the function is running). But because closure preserves the value of the variable even after the parent function (add) has finished execution, the other functions (addFunc) that are that are using the parent function are able to access the variable. Hope that helps. :)
No, don't feel stupid. It's hard to wrap your head around closures. From my experience so far, not much programming is intuitive. The takeaway at 6:28 is what you should consider imo
5:07 - innerfunction() will only have access to those variables of outerfunction() which innerfunction() wants to use it. , when we do console.dir( newFunction ) , we can see [ [Scopes] ] Array , which has Closure Object with the variables that would be used by innerfunction() only , not all variables of outerfunction
The first example you gave is not due to closure but due to scope chaining. Closures come in play when the execution context has finished but the variables still stay around. In first example we still have global execution context. But thanks for video always learn something new everyday.
Thank you, Kyle. Your explanation is so good that other people's closure videos starting making sense to me too. You simplify web development so successfully that I always benefit from your channel since I started learning JavaScript!
Kyle, thanks to your videos I learned not only JS but English too. I don't know how but you clarified and simplified all info in your videos so well, hope so youtube algorithm make you famous, good luck :)
After 10 thousand videos, I was finally able to wrap my head around this passing of param straight to the inner function and not to the outer one, starting at: 3:48
In other languages, the global variables are accessible everywhere. Variables in parent functions are accessible to inner functions. Variables in parent classes are accessible in the class functions as well as in child classes and their functions. (if set up as public or protected).
The thing that is very confusing with this example is that the outer function RETURNS a function. I needed a long time to understand it but finally did. After the statement: const newFunction = outerFunction('outside') the VALUE of newFunctio will be what is inside the RETURN clause, so, de VALUE of "newFunction" will be: "function innerFunction(innerVariable) { ....console.log('outer variable', 'outside'); ....console.log('inner variable', innerVariable); } The confusing part is that when the function is returned, the part that logs "innerVariable", no longer logs innerVariable, it logs 'outside' instead because it is what has ben passed as parameter when the outer function was called. So, when you execute newFunction('inner') you are executing the function that has been returned the first time. So you are basically executing this: newFunction('inner'){ ....console.log('outer varaible', 'outside'); //this 'outside' is a literal value (not a variable) assigned when newFunction was assigned ....console.log('inner variable', 'inner'); //this 'inner' was passed as a parameter when calling newFunction('inner'); } I hope this calrifies. The whole closures thing is not that complicated. Basically, you can always access variables/functions/etc that are in a higher scope than you are standing. You could see it as if the function/variable/etc is LESS INDENTED (further to the left) in your code, you can access it.
Man, congrats about your videos. I passed in a interview using your videos about React to learn how to build an app and now I'm using again. Continue this job.
Finally I funckin' got it. Thanks Kyle. I found myself coming back to your channel more and more when I need to clarify/understand some webdev-related stuff. Will definitely buy at least one of your courses. Keep up the good work.
This closure topic was so difficult to understand at first. I've read it on multiple sites but this video by Kyle is really awesome and easy to understand. Thank you Kyle!
Closures Explained in simple words => inner scopes can access variables defined in outer scopes & outer scopes can not access variables defined in inner scopes.
Tomorrow i have an interview. I was thinking what i don't understand or know that well and i was searching right now to see what i can find. Closures were the first item on the list. Are you reading your subscribers minds? Thank you for this tutorial. Other items on list are call&apply and bind.
Thank you. I think I understood. I was expecting closures to be something more "visible", a specific keyword, or a line where I could comment next to it. But if I understood it right, it's more like a concept, like a behavior of an inner function.
The thing is that I was confused between lexical environment and closures. Lexical environment is just the area the item(for example a function) was declared in and that area dictates what data the item has access to. Closures are inner functions that are enclosed(and returned) by an outer function but the inner function in question still has access to the lexical environment. The thing that makes closures work is if you call the outer function and store it in a variable then the inner function will remember/store the data from the outer function in its own little world. I hope I explained well enough.
It's just like saying that inner function has its own spatial memory which collects info about its surrounding environment which consists of variables and/or functions and know the routes to reach any of them.
The outerFunction is the parent function and the innerFunction is the child. The outerFunction passes on it's genes that, right before dying, lives on in the child to continue the outerFunction's legacy.
@@Microphunktv-jb3kj This is why they get ride of callbackhells with Promises, and later on, they added Async/Await which is by far more easier and cleaner to understand and write. Don't push yourself if you don't get this at first glance, this is hard for everyone. Things get better with practice and from day to day, put effort on making simple and understandable code that everybody can understand. :)
In a sense, closures are objects... Calling the outer function multiple times with different arguments will create *different* closure instances, and calling the associated returned functions will access the associated closure contents. So, they're objects!
Thank you very much Kyle for the nice explanation. Closure was not clear exactly to me until I watched your video, That makes the understanding more easier
Great video! Exactly! Why make it so complicated. An inner function has access to the outer functions variables and scope even after it has been called.
So well explained! I'm fan of your videos since saturday! Thank you!! May be one thing missing in this one is to explain what happens when an outside variable gets modified inside a function (because i thinks it's not like php where you have to pass it as a reference and all that). Anyway, you rule. One of the best channels for learning! And the short video distribution is awesome to watch them at any time of the day.
I had one question for you that since you have already been crossed 90k+ and you're on the way to get 100k so what's your experiences on RUclips likely to be? Does people like more videos on how to do/know certain topics like this one or detailed & long in-depth analysis like your full stack MERN course/project based approach
It really depends. People like both types of videos and in general a project based video will probably do better than a video like this, but it is hard to say.
Still confusing. At 3:45 it makes perfect sense not to have access to outerVariable because it's not defined in global scope. It's a function parameter. The part where it gets unfamiliar is at 4:26, where we pass nothing, yet the previous call's values are accessible -- newFunction() 6:00 is not quite as obvious because to many it's not obvious how promise chaining works. I'd also assume that closures would ordinarily be covered earlier than fetch in any js course. Please correct me if I err.
this has to be the most difficult thing i've ever learned in programming, not just closures, but trailing, capture and escaping closures, and i thought learning every major design pattern for swift, dart and js was hard
Good explanation mate, I subscribed!. tip: You really should start using the semicolons while writing javascript code, and avoid using anonymous functions, you should name those functions even if they are IIFEs or arrow functions, it makes debugging easier since the function name shows up on the errors later..
Kyle you are awesome! Thank you for this! I’m constantly coming to your videos! Trying to learn as much as I can but really trying to understand how things work!
I'm still a bit confused how the inner variable ended up getting the value of 'inside' :( But I'll keep trying to understand it! I would like to understand JS more!
Wait... I watched this other video that explains functions returning functions... so that part mentioned in my earlier comment, those last two lines are basically the same as this? >> outerFunction('outside')('inside') Then it would first run the outerFunction('outside') to fill the first part of the result, then the ('inside') runs for the second part of the results? Sorry if follow up post sounds all confusing lol. It's hard to explain while trying to wrap my head around this.
@@NbaLive4ever So basically if you take the last two lines one by one: "const newFunction = outerFunction('outside')", this is saying 1. execute outerFunction passing in the string variable "outside" and 2. assign whatever it returns to the const variable newFunction. If we look at what the outerFunction returns, we can see that its "function innerFunction(..)" i.e. it's of type function. It's at this point the concept of closure is at work as not only is the function returned but part of the code within the returned the function uses a variable from an outer scope (this is the variable "outerVariable"). I visualise this as when a function is returned it takes a snapshot of any variable the function uses and that variable is boxed into the overall value of the function. Continuing to the next line "newFunction("inside")": We just created newFunction on the previous line and gave it the returned value of the outerFunction, which turned out the be a function (which takes one parameter "innerVariable"). Therefore we are able to call newFunction as a function and pass it a string variable "inside" and this is used in the second console.log .
The thing that is very confusing with this example is that the outer function RETURNS a function. I needed a long time to understand it but finally did. After the statement: const newFunction = outerFunction('outside') the VALUE of newFunctio will be what is inside the RETURN clause, so, theVALUE of "newFunction" will be: "function innerFunction(innerVariable) { ....console.log('outer variable', 'outside'); //here 'outside' is a literal since it was assigned when newFunction was assigned ....console.log('inner variable', innerVariable); //here innerVariable is a variable passed as a parameter }
Closures are probably the most difficult notion to grasp in javascript. It would be interesting to insist on the fact that the current value is used, because closures are often into play in asynchronous callbacks.
I have a question I've been wanting to make for a while.. why dont you have to use ";" at the end of the code line? Sorry if it's a stupid question but i can't get any sleep at night thinking about this
I am on my way to understand this. Thanks a lot for helping me, i think i cant understand this at 100%, but i will not give up. Im learning a lot with you and your youtube channel. You got a new subscriber here. Cheers! And thanks again!
So it's just a corollary of scope and, in the case of JavaScript, a scope that is maintained for the duration of the script's run and one whose state is current. An useful example might be the script for a slideshow on a web page. The whole website has a single script file, mysite.js, and this contains an IIFE called SLIDESHOW. SLIDESHOW in turn has some global variables, e.g. slideIndex, and some subsidiary functions like prev(), next(), pauseRplay(), etc. The latter functions are associated with user buttons for and II / > . The SLIDESHOW IIFE will *return* these subsidiary functions so they are accessible outside SLIDESHOW and callable via something like SLIDESHOW.next(), SLIDESHOW.pauseRplay(), etc. Because each of the subsidiary functions have closure on the slideIndex value, they can rewind/advance/pause/restart correctly from the current slide and have the new slideIndex value incremented and saved.
Inner functions and outer functions, variable accessibility and the weird way javascript works, that's how I'm gonna remember closures when someone asks me in my next interview.
This might sound stupid but if with closures we had access to outer scope as well then why was arrow notation introduced with es6. I mean “this” would have been passed as well since it is used to scope the context of inner functions with outer functions. 🤨🤨🤨
no you have misunderstood this, each function has it's own "this" yes all functions have access to all of their parents data but when you define a normal function it overwrites "this" inside itself so if you try to access "this" inside this new normal function it will refer to the child function's "this". but arrow functions don't overwrite "this" inside them and refer to their parent's "this"
Although your explanation was wonderfully easy and extraordinary than other tutorials, there's one problem for me which is the self-invoking function or the returned nested function, I didn't understand this in the beginning because is usually write C#, and I don't usually see this formation, and it kept confusing me till I searched about that and understand this finally but very thanksssss
**If you are confused about his code example, please see my 3 step explanation:**
1. The outerFunction('outside') is called immediately when it is assigned to the variable "newFunction". (That's how it works when a function is assigned to a variable with (), if you didn't know this part, you would very confused).
2. Upon being called, outerFunction returns the function "innerFunction(innerVariable") which re-reassigns our variable "newFunction" to be InnerFunction(innerVariable) instead of outerFunction(outerVariable).
3. Then by calling our variable as newFunction('inside') we are calling innerFunction('inside') which runs the console.log code. The closure is that innerFunction remembers and has access to the outerVariable parameter we originally set with outerFunction('outside'). Thus it is able to console.log both 'outside' and 'inside' even though it was called with just 'inside'.
If this helped you please thumbs up so others can see!
thanks... it took a while to understand this concept and your explanation helps me re-confirm that what I understand is true.
Thanks man 👍👍
Thanks brother it really helped me
Thanks, I was so confused when I saw that.
great explanation,thank you!
SUMMARY: Closure i s "when you have a function defined inside of another function, that inner function has access to the variables and scope of the outer function even if the outer function finishes executing and those variables are no longer accessible outside of that function."
Ha-ha! A truly brilliant explanation by Kyle!
Thank you
Check out this too - ruclips.net/video/W7j1jcOoMt0/видео.html
Now I finally understand closures. Thanks for this summary.
You should get Nobel price
*personal note*
newFunction call = (outerFunction + calling it).
outerFunction executes, returning innerFunction while passing in "outside" as part of the accessible scope.
newFunction then passes "inside" to the now returned innerFunction, calling it and completing the execution.
For anyone reading, I have no idea if I'm right but this makes sense to me rn.
Analogy note: newFunction is like the first car key turn, it activates the starter (outerFunction) which primes the engine by passing in "outside" and returning innerFunction as ready to ignite. The second turn is newFunction passing in "inside" which sends fuel, igniting the engine (calling innerFunction)
Nice, love this analogy
I think I FINALLY understand closures. In fact, I found a good reason to use one today in my project. TLDR; When you need to pass a function with no parameters, but the function you want to pass has parameters. BAM, create a closure by putting the variables/parameters you need in the outer function and return a function with no parameters (just remember that returned function has access to the outer function parameters, even after it's done executing).
Closures are such an interesting topic that I always watch anyone or everyone coming up with an explanation for the same. This was one of the best explanations that I have come across.
Thank you!
10-second summary: 6:28
OK, i am taking it since i don't understand anything else
thank you lol
it's been 70 years and I still don't understand closures
You are not alone.
Jump to 6:27
Haha okay one tip for you. If you are smart enough you would understand. Javascipt variables do not holds the values they rather holds the references to the physical memory slots in which values are contained. When variables are returned from a function , it forms a closures because the function is not returning the variables/values, the function is rather returning the references to memory slots .. That's it
try having a look at this once: ruclips.net/video/ZA3ogWqNNPg/видео.html
but javascript is only 23 or 24 yrs old
It’s just a child function having access to its parents function
There's more to it. That's actually lexical scope. Lexical scope comes into play in the concept of Closures when that lexical scope is 'closed' out, hence the term closure. A Closure is when you still have access to a lexical scope that has been closed and the values should have been garbage collected are still available to your closure / function that is still accessing them.
@@SquaredbyX to see if I got it right, its like the inner scope creates a copy of the outer one for "personal use", right?
@@SquaredbyX You really hit it home with that explanation. Thank you!
So what the use of the closure then?
@@kobe248ryant nothing just use the parent scope in the child scope
I was confused all along but your last sentence saved me 😁
Same bro i got confused too
Same here
same
That last sentence saved me too.
You saved me lok
i always come back to this channel whenever i need a clear , simple and straight to the point explanation
I watched many videos on closures but everybody trying to explain too much and somewhere lose the real thing. Your example and explanation are good. I got the concept. thank you for this video.
Closures allow functions to access variable values, declared in another (parent) function, even after the parent function has finished it's execution.
In js, the variables within a function are accessible only within itself and only for as long as the function is executing.
You can understand this, by creating a new variable and assigning the parent function to that variable. Then do 'console.dir(new variable).
Try below example :
const add = function(){
let num = 1;
return function() {
num++
return num;
}
}
const addFunc = add()
console.dir(addFunc)
in the console > click on 'f anonymous()' > click on 'scopes' > click on 'closure'
In the above example, the addFunc function is declared in the global scope. Hence, it should not be able to access the variable in the add function, because variables can only be accessed within the scope and and while the scope still exists (as long as the function is running). But because closure preserves the value of the variable even after the parent function (add) has finished execution, the other functions (addFunc) that are that are using the parent function are able to access the variable.
Hope that helps. :)
So in simple terms a closure is when an inner function remembers the variables of the outer function even when the outer function is done executing.
Watched the vid 3 times and still not getting it. I feel stupid
No, don't feel stupid. It's hard to wrap your head around closures. From my experience so far, not much programming is intuitive. The takeaway at 6:28 is what you should consider imo
read the book of kylie Simpson - you don't know javascript
Try looking at this once: ruclips.net/video/ZA3ogWqNNPg/видео.html
I hope it will help.
ruclips.net/video/nG4tqI-9K3o/видео.html
Thats because the man in the video himself is confused
5:07 - innerfunction() will only have access to those variables of outerfunction() which innerfunction() wants to use it. , when we do console.dir( newFunction ) , we can see [ [Scopes] ] Array , which has Closure Object with the variables that would be used by innerfunction() only , not all variables of outerfunction
Great video. I watched this a month before my interview but forgot the concept so I recommend y'all watch it again every now and then
The best explanation on RUclips, thank you very much. I don't know why ppl keep complaining about not understanding this.
Thanks for that Axios example, which no one ever has mentioned in their closure tutorial. We were using closures without even realizing it.
The first example you gave is not due to closure but due to scope chaining. Closures come in play when the execution context has finished but the variables still stay around. In first example we still have global execution context. But thanks for video always learn something new everyday.
right. this is what i was thinking
Thank you, Kyle. Your explanation is so good that other people's closure videos starting making sense to me too.
You simplify web development so successfully that I always benefit from your channel since I started learning JavaScript!
I am so glad I could help!
Kyle, thanks to your videos I learned not only JS but English too.
I don't know how but you clarified and simplified all info in your videos so well, hope so youtube algorithm make you famous, good luck :)
Thank you so much! I'm really glad I can help.
After 10 thousand videos, I was finally able to wrap my head around this passing of param straight to the inner function and not to the outer one, starting at: 3:48
You tried to simplify the concept from the start and made your point clear. Thank you.
2:34." When most people think of closures they think of function inside a function." That has been the problem for me. Thanks for the clarification
6:28 after watching the video once, repeat this for 5 times and you're good. Once more, thank you Kyle :)
In other languages, the global variables are accessible everywhere.
Variables in parent functions are accessible to inner functions.
Variables in parent classes are accessible in the class functions as well as in child classes and their functions. (if set up as public or protected).
The thing that is very confusing with this example is that the outer function RETURNS a function. I needed a long time to understand it but finally did.
After the statement: const newFunction = outerFunction('outside') the VALUE of newFunctio will be what is inside the RETURN clause, so, de VALUE of "newFunction" will be:
"function innerFunction(innerVariable) {
....console.log('outer variable', 'outside');
....console.log('inner variable', innerVariable);
}
The confusing part is that when the function is returned, the part that logs "innerVariable", no longer logs innerVariable, it logs 'outside' instead because it is what has ben passed as parameter when the outer function was called.
So, when you execute newFunction('inner') you are executing the function that has been returned the first time.
So you are basically executing this:
newFunction('inner'){
....console.log('outer varaible', 'outside'); //this 'outside' is a literal value (not a variable) assigned when newFunction was assigned
....console.log('inner variable', 'inner'); //this 'inner' was passed as a parameter when calling newFunction('inner');
}
I hope this calrifies.
The whole closures thing is not that complicated. Basically, you can always access variables/functions/etc that are in a higher scope than you are standing. You could see it as if the function/variable/etc is LESS INDENTED (further to the left) in your code, you can access it.
Man, congrats about your videos. I passed in a interview using your videos about React to learn how to build an app and now I'm using again. Continue this job.
Finally I funckin' got it. Thanks Kyle. I found myself coming back to your channel more and more when I need to clarify/understand some webdev-related stuff. Will definitely buy at least one of your courses. Keep up the good work.
This closure topic was so difficult to understand at first.
I've read it on multiple sites but this video by Kyle is really awesome and easy to understand.
Thank you Kyle!
Closures Explained in simple words =>
inner scopes can access variables defined in outer scopes & outer scopes can not access variables defined in inner scopes.
i was learning on Udemy and i got some trouble to understand ...after watching this video it was easy peasy to understand ... thanks so much
Tomorrow i have an interview. I was thinking what i don't understand or know that well and i was searching right now to see what i can find. Closures were the first item on the list. Are you reading your subscribers minds? Thank you for this tutorial. Other items on list are call&apply and bind.
Good luck with the interview!
Thanks for this! I watched this after a lecture and watching a few other videos that confused me... I finally got it!
Thank you. I think I understood. I was expecting closures to be something more "visible", a specific keyword, or a line where I could comment next to it. But if I understood it right, it's more like a concept, like a behavior of an inner function.
this is still the best explanation of this concept. never fails me
The thing is that I was confused between lexical environment and closures. Lexical environment is just the area the item(for example a function) was declared in and that area dictates what data the item has access to. Closures are inner functions that are enclosed(and returned) by an outer function but the inner function in question still has access to the lexical environment. The thing that makes closures work is if you call the outer function and store it in a variable then the inner function will remember/store the data from the outer function in its own little world. I hope I explained well enough.
i have tried so many videos on youtube but none of them explained in the way you did, thank you so much for a nice video.
Read atleast 10 articles to understand closures.. but this one saved me
It's just like saying that inner function has its own spatial memory which collects info about its surrounding environment which consists of variables and/or functions and know the routes to reach any of them.
I learn about closures on MDN, highly recommended!
Finally, I am able to understand closure. Thanks!!!
That was simple, because you made me understand it in a simpler way. Thanks Kyle. 😊
Watched 1 minute of your video and understood closures. Thanks!
This is great, appreciate you not making it more complicated than it needs to be. Thanks!
this is nuts why the JS guys design something like this!
The outerFunction is the parent function and the innerFunction is the child. The outerFunction passes on it's genes that, right before dying, lives on in the child to continue the outerFunction's legacy.
i love you and your channel i hadn't seen anyone explaining js closures as clear as you
Thank You So Much for this wonderful video..........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
Skip to 6:28
Question, when and why would you use closures? I'm new to coding and I am learning closures now.
Today I had an interview and the interviewer asked me about closure. I did not give a proper answer and now I am here :).
You are a legend, always glad to come back to these videos and brush up the fundamentals again
Kyle is good when it comes to explanation. Thank you
function returns another function, when should i use it in real life project, could you please explain it?
i am suffering to understand it.
You should not. You should write your code as you live your life. As simple as possible.
@@Microphunktv-jb3kj This is why they get ride of callbackhells with Promises, and later on, they added Async/Await which is by far more easier and cleaner to understand and write.
Don't push yourself if you don't get this at first glance, this is hard for everyone. Things get better with practice and from day to day, put effort on making simple and understandable code that everybody can understand. :)
In a sense, closures are objects...
Calling the outer function multiple times with different arguments will create *different* closure instances, and calling the associated returned functions will access the associated closure contents.
So, they're objects!
Thank you very much Kyle for the nice explanation. Closure was not clear exactly to me until I watched your video, That makes the understanding more easier
Great video! Exactly! Why make it so complicated. An inner function has access to the outer functions variables and scope even after it has been called.
What happened to the comment by the guy that still doesn't understand even though it been 70 years? Also not finding Vlad's explaination.
So well explained! I'm fan of your videos since saturday! Thank you!! May be one thing missing in this one is to explain what happens when an outside variable gets modified inside a function (because i thinks it's not like php where you have to pass it as a reference and all that). Anyway, you rule. One of the best channels for learning! And the short video distribution is awesome to watch them at any time of the day.
Thank you so much. I have a video on pass by reference vs pass by value in JS that you can checkout that explains exactly this concept.
Most straight forward easy to understand explanation I've seen. Thanks buddy.
The last example was amazing! Thank you for taking the time to make this!!
I had one question for you that since you have already been crossed 90k+ and you're on the way to get 100k so what's your experiences on RUclips likely to be? Does people like more videos on how to do/know certain topics like this one or detailed & long in-depth analysis like your full stack MERN course/project based approach
It really depends. People like both types of videos and in general a project based video will probably do better than a video like this, but it is hard to say.
@@WebDevSimplified thanks for it Kyle...♥️
Still confusing.
At 3:45 it makes perfect sense not to have access to outerVariable because it's not defined in global scope. It's a function parameter. The part where it gets unfamiliar is at 4:26, where we pass nothing, yet the previous call's values are accessible -- newFunction()
6:00 is not quite as obvious because to many it's not obvious how promise chaining works. I'd also assume that closures would ordinarily be covered earlier than fetch in any js course. Please correct me if I err.
this has to be the most difficult thing i've ever learned in programming, not just closures, but trailing, capture and escaping closures, and i thought learning every major design pattern for swift, dart and js was hard
Good explanation mate, I subscribed!. tip: You really should start using the semicolons while writing javascript code, and avoid using anonymous functions, you should name those functions even if they are IIFEs or arrow functions, it makes debugging easier since the function name shows up on the errors later..
This made closures so simple. Thanks!
Kyle you are awesome! Thank you for this! I’m constantly coming to your videos! Trying to learn as much as I can but really trying to understand how things work!
Loving this community
Man,why are you not getting views,so underrated..
Nice video but what is the advantage to use closure , why we need closure? please reply
there is no advantage or disadvantage, and you don't need to use them.. you simply can not-not use them.. is how the language works
I finally understand it after your explanation. You should do a udemy course
Excelent explanation, thank you a lot, I was having trouble trying to understand Closures, and this video fit like a glove!
I'm still a bit confused how the inner variable ended up getting the value of 'inside' :( But I'll keep trying to understand it! I would like to understand JS more!
Wait... I watched this other video that explains functions returning functions... so that part mentioned in my earlier comment, those last two lines are basically the same as this? >> outerFunction('outside')('inside')
Then it would first run the outerFunction('outside') to fill the first part of the result, then the ('inside') runs for the second part of the results? Sorry if follow up post sounds all confusing lol. It's hard to explain while trying to wrap my head around this.
@@NbaLive4ever So basically if you take the last two lines one by one:
"const newFunction = outerFunction('outside')", this is saying
1. execute outerFunction passing in the string variable "outside" and
2. assign whatever it returns to the const variable newFunction.
If we look at what the outerFunction returns, we can see that its "function innerFunction(..)" i.e. it's of type function. It's at this point the concept of closure is at work as not only is the function returned but part of the code within the returned the function uses a variable from an outer scope (this is the variable "outerVariable"). I visualise this as when a function is returned it takes a snapshot of any variable the function uses and that variable is boxed into the overall value of the function.
Continuing to the next line "newFunction("inside")":
We just created newFunction on the previous line and gave it the returned value of the outerFunction, which turned out the be a function (which takes one parameter "innerVariable"). Therefore we are able to call newFunction as a function and pass it a string variable "inside" and this is used in the second console.log .
The thing that is very confusing with this example is that the outer function RETURNS a function. I needed a long time to understand it but finally did.
After the statement: const newFunction = outerFunction('outside') the VALUE of newFunctio will be what is inside the RETURN clause, so, theVALUE of "newFunction" will be:
"function innerFunction(innerVariable) {
....console.log('outer variable', 'outside');
//here 'outside' is a literal since it was assigned when newFunction was assigned
....console.log('inner variable', innerVariable);
//here innerVariable is a variable passed as a parameter
}
You made this concept very easy. Thank you Kyle.
Great job buddy, I like the sequence you presented it in: simple example, better example and then use case.
The confused look in the thumbnail 🤣
Closures are probably the most difficult notion to grasp in javascript. It would be interesting to insist on the fact that the current value is used, because closures are often into play in asynchronous callbacks.
I have a question I've been wanting to make for a while.. why dont you have to use ";" at the end of the code line? Sorry if it's a stupid question but i can't get any sleep at night thinking about this
Semi-colons are optional in JS so I just don't use them.
@@WebDevSimplified the real question is who's idea was it to make it optional and why?
best explanation ever
kyle resisted the terminator, now he changed the mission to simply web dev!!
it is basically the function with lexical environment(parent environment).
*he: passionately explain everything you need to know
*me: look at screen and have no idea
*also he: 6:29
*me: yeah that make sense!
I am going to download all your video and tranform them into mp3 audios and listen to them to fall asleep at every night. I hope you don't mind.
I am on my way to understand this.
Thanks a lot for helping me, i think i cant understand this at 100%, but i will not give up.
Im learning a lot with you and your youtube channel.
You got a new subscriber here.
Cheers! And thanks again!
great explanation ........ keep on uploading more concepts videos...
You are gem to people who want to learn web development on own.....
does the innerFunction have access to the global scope? or just to the immediately superior function?
Yes it does also have access to the global scope.
Thanks :)
that is why it's called "global", everyone can access it
So it's just a corollary of scope and, in the case of JavaScript, a scope that is maintained for the duration of the script's run and one whose state is current.
An useful example might be the script for a slideshow on a web page.
The whole website has a single script file, mysite.js, and this contains an IIFE called SLIDESHOW.
SLIDESHOW in turn has some global variables, e.g. slideIndex, and some subsidiary functions like prev(), next(), pauseRplay(), etc. The latter functions are associated with user buttons for and II / > .
The SLIDESHOW IIFE will *return* these subsidiary functions so they are accessible outside SLIDESHOW and callable via something like SLIDESHOW.next(), SLIDESHOW.pauseRplay(), etc.
Because each of the subsidiary functions have closure on the slideIndex value, they can rewind/advance/pause/restart correctly from the current slide and have the new slideIndex value incremented and saved.
Inner functions and outer functions, variable accessibility and the weird way javascript works, that's how I'm gonna remember closures when someone asks me in my next interview.
Really good content man. Thanks for explaining it clear and concise!
Ooo boy, this helped me understand the concept. Thanks !!
Thanks Kyle!
awesome... I finally understood what closure is
This might sound stupid but if with closures we had access to outer scope as well then why was arrow notation introduced with es6. I mean “this” would have been passed as well since it is used to scope the context of inner functions with outer functions. 🤨🤨🤨
no you have misunderstood this, each function has it's own "this" yes all functions have access to all of their parents data but when you define a normal function it overwrites "this" inside itself so if you try to access "this" inside this new normal function it will refer to the child function's "this". but arrow functions don't overwrite "this" inside them and refer to their parent's "this"
Wow I think this just clicked for me. Took me watching this a few times but the inner/outer variables seem to have helped.
in which language can't we access global variable?
Although your explanation was wonderfully easy and extraordinary than other tutorials, there's one problem for me which is the self-invoking function or the returned nested function, I didn't understand this in the beginning because is usually write C#, and I don't usually see this formation, and it kept confusing me till I searched about that and understand this finally but very thanksssss
This explanation was great! Thankyou for the video.
You make everything super easy..! Thanks a lot.
Summed up great at the end.