Demystifying JavaScript Closure

Поделиться
HTML-код
  • Опубликовано: 2 окт 2016
  • JavaScript closure is sometimes not fully understood. In this tutorial from All Things JavaScript we attempt to demystify the concept through multiple JavaScript examples.
    Would you like to help keep this channel going?
    / allthingsjavascript
    For a complete list of all our tutorials:
    www.allthingsjavascript.com/yo...
    Access to EVERY course (get 2 months free): www.skillshare.com/r/profile/...
    Courses offered on Udemy at a discount (access from my site): allthingsjavascript.com/course...
    #javascript #AllThingsJavaScriptLLC

Комментарии • 96

  • @taljune142010
    @taljune142010 5 лет назад +12

    Thanks a lot! I watched many explanations and only yours is clear and easy understand.

  • @truthalwaysprevails662
    @truthalwaysprevails662 5 лет назад +11

    I had this ''a ha" moment right now!

  • @praxisdev1884
    @praxisdev1884 5 лет назад +4

    Extremely well explained, thank you. I’m a fan!

  • @SabrinaMarkon
    @SabrinaMarkon 6 лет назад +4

    Your tutorials are absolutely marvelous! I think they provide a great deal of clarity (a-ha's) about the complexities of JavaScript. Thank you so much for sharing them with us!

    • @AllThingsJavaScript
      @AllThingsJavaScript  6 лет назад +1

      Thank you for your positive feedback! I really appreciate it.

  • @ariosetiawan173
    @ariosetiawan173 4 года назад +1

    Clear, Detail and not too fast when explaining...

  • @stargazer3049
    @stargazer3049 4 года назад +1

    You explain things so incredibly well! Thank you!

  • @sandun4983
    @sandun4983 2 года назад

    This channel is truly gem mine for every one who is finding their self in programming ..

  • @kineticBoss
    @kineticBoss 6 лет назад +2

    Thanks a lot for this crisp tutorial. Very neat

  • @akkineniajay8117
    @akkineniajay8117 6 лет назад +3

    Very neatly explained. Thanks!

  • @josemaribautista7552
    @josemaribautista7552 4 года назад

    this is one of the better explanations on this topic. Thanks!!

  • @joeltorres1237
    @joeltorres1237 5 лет назад

    Great example using the colored code. Great work creating these code snippets!

  • @ArjunSarthi
    @ArjunSarthi 4 года назад +5

    Sir, You are a Genius.. I watched so many videos till now to understand Closures. But your video, Damn....You made it look Easy..Now I can explain this to anyone..I am a fan of yours :)

    • @AllThingsJavaScript
      @AllThingsJavaScript  4 года назад

      Thanks for the feedback!!

    • @ArjunSarthi
      @ArjunSarthi 4 года назад +1

      @@AllThingsJavaScript sir..I want to contribute something..how can I do it?..please guide me

    • @AllThingsJavaScript
      @AllThingsJavaScript  4 года назад

      Thanks for asking! I appreciate the support. It helps me to continue doing this. This link provides a couple of options: allthingsjavascript.com/contribute.html

  • @thatsforrealmusic6884
    @thatsforrealmusic6884 4 года назад

    Wow!! This clarify closure a lot for me and its a powerful technique!

  • @greenworld7085
    @greenworld7085 4 года назад

    I'm loving your explanation more and more as I watch your videos. U are really good at explaining these concepts. I really appreciate these good hard works U put on each videos. Thanks a lot.

  • @raymondmichael4987
    @raymondmichael4987 4 года назад +2

    I caught my "A Ha" moment at the module part; truly, CLOSURE is such a powerful knowledge and thanks to you for demystifying it.
    Keeep it up
    Greetings from Tanzania 🇹🇿

  • @Zen-lz1hc
    @Zen-lz1hc 3 года назад

    Really great video on javascript closures .
    Thank You Very Much :)

  • @demiansims728
    @demiansims728 4 года назад

    These are the best and clearest tutorials on the deeper aspects of Javascript. Watch these videos if you REALLY want to understand JS.

  • @NoOne-om9bb
    @NoOne-om9bb 5 лет назад

    God bless u sir even after a year it helped me, thank you very very much sir!

  • @blahblahblah2070
    @blahblahblah2070 5 лет назад

    Very clear and precise....thx a million

  • @inkiosi9790
    @inkiosi9790 3 года назад

    This was the best explanation of closure I ever found. Thanks a lot!

  • @MrTravelingThrough
    @MrTravelingThrough 3 года назад

    This guy is a great teacher.

  • @vipinsharma1984
    @vipinsharma1984 7 лет назад

    Thanks. Very clearly explained.

  • @shahidhabib88
    @shahidhabib88 3 года назад

    Great video, thanks!

  • @MrRobeezy29
    @MrRobeezy29 3 года назад

    Thank you for this - finally a clear explanation. Perfect example of "if you can't explain it simply you don't really understand it" - Einstein

  • @artli5970
    @artli5970 4 года назад

    thank you. your explanation is excellent.

  • @russelldriver6394
    @russelldriver6394 3 года назад +1

    This was the most fantastic explanation ever! Good Job and thanks :)

  • @jeremymitchell3554
    @jeremymitchell3554 Год назад

    I found this concept to be easy to grasp. I give credit to your amazing ability to teach these concepts. Thanks for the hard work you put into these videos.

  • @AbhijitChandekar
    @AbhijitChandekar 4 года назад

    you explained it very well! thanks a lot!!!!

  • @kiwi-Centaur
    @kiwi-Centaur 2 года назад

    Thanks a lot for uploading this video, it was really helpful and informative, keep up the good work. cheers

  • @rahulroy463
    @rahulroy463 2 года назад +1

    watch one after another aswm :) please keep up the great work. :)

  • @_darkbrian
    @_darkbrian 5 лет назад +1

    A-Ha modules are amazing stuff!

  • @AYUSHSHARMAblogs
    @AYUSHSHARMAblogs 2 года назад

    Nicely explained

  • @eugeniogonzato
    @eugeniogonzato 4 года назад

    Thanks, very well explain

  • @xiaosage
    @xiaosage 5 лет назад +1

    good teacher !

  • @iitandmedical8528
    @iitandmedical8528 5 лет назад

    wonderful sir

  • @haciendadad
    @haciendadad 4 года назад +1

    Just a tip. If you have anything above that IFFE like a variable or another function and it doesn't have a semicolon after it, you get this ugly unexplainable error. Add a semicolon and the IFFE works. To see what I ran into, see it here: stackoverflow.com/questions/42036349/uncaught-typeerror-intermediate-value-is-not-a-function

  • @haciendadad
    @haciendadad 4 года назад +1

    So considering we are discussing scope, I would like to know if using let or const instead of var would change anything in closures?

    • @AllThingsJavaScript
      @AllThingsJavaScript  4 года назад +3

      If you mean are the values still enclosed, yes they are as long as what you are trying to access has the proper scope. Remember that let and const are block scoped. If that block is the function, then you would have access.

  • @carolinerussell8122
    @carolinerussell8122 5 лет назад

    a true god among us.

  • @itsdannyftw
    @itsdannyftw 6 лет назад +1

    Hi Stephen, thanks for your videos. May I ask what do you cover differently in your Udemy courses? i.e. the closure video in your Udemy course, appears to be less in duration (11minutes), does that indicate All Things Javascript goes into more details / slower (thus ideal for a beginner)? I am trying to determine whether or not there is any additional benefit in purchasing the course, or are these videos sufficient? i.e. what is the benefit in purchasing the course? Or is All Things Javascript, a better, more improved set of videos, based on the feedback you have obtained from your Udemy course(s)?

    • @AllThingsJavaScript
      @AllThingsJavaScript  6 лет назад +2

      Good question! Yes, I feel the courses are a benefit for a few of reasons: 1. I cover topics in a progressive pattern so concepts build on each another, and 2. I feel I go into more depth. You are correct the closure video is shorter, but closure is touched on numerous times and used in laters examples. And finally there are topics in the courses that have not made it onto the RUclips channel. It is probably worth noting that the videos on the courses and those on the channel are never the same. Sometimes two different explanations can by helpful if the concept is difficult. I hope that gives you enough information to make a decision. Either way I appreciate you commenting on these videos.

    • @itsdannyftw
      @itsdannyftw 6 лет назад

      Thanks for your reply, appreciate all the videos.

  • @toannew
    @toannew 3 года назад

    return functions from a function 14:01

  • @saimonish9640
    @saimonish9640 5 лет назад +1

    Hi.. Loving your tutorials so far!! Very simple and clear ones..
    In this one I didn't understand how the callback functions have access to the variables.. The one where you have event listeners example how does it have access to variables. It is still present inside a global function scope of counter right?

    • @AllThingsJavaScript
      @AllThingsJavaScript  5 лет назад +1

      The reason they have access to the variable is because of closure. The outer function creates closure over all the variables. So for the listener, those variables still exists. It is one of the great features of JavaScript.

    • @saimonish9640
      @saimonish9640 5 лет назад

      @@AllThingsJavaScript so in case of array map function which is used inside a function.. We usually assign the variables with values iterated inside the map function. Does that mean higher order functions also are closures?

    • @AllThingsJavaScript
      @AllThingsJavaScript  5 лет назад +2

      @@saimonish9640 Closure applies to the scope the function is running in. So if a function is running in a scope it would have closure over the items in that scope, even if the function has completed. So, it doesn't matter if it is higher order or not, it has to do with the scope of the function. So in the case of map etc. new values are passed in each time it iterates, so really not closure, but it could use closure for other variables. Here is a tutorial on those array functions if you need it: ruclips.net/video/RePO4I6PzSA/видео.html

    • @saimonish9640
      @saimonish9640 5 лет назад

      @@AllThingsJavaScript thanks for the replies! 👍

  • @insydium7385
    @insydium7385 3 года назад

    Thank you! I feel less dumb now

  • @demiansims728
    @demiansims728 4 года назад

    I notice that 'funct2' isn't called in the async function 'timeout() arguments" . I guess it's called by the 'timeout()' itself?

  • @Sam-cz7ck
    @Sam-cz7ck 3 года назад

    Great video, full of A-ha momennts!

  • @stephblank8204
    @stephblank8204 2 года назад

    If I were to work through your videos, where do you suggest I start?

    • @AllThingsJavaScript
      @AllThingsJavaScript  2 года назад +1

      I have a getting started playlist that contains most of the basic tutorials I've created. That is probably the best place to start: ruclips.net/p/PLTo9PCskHpbHjtO9Dq4gC0DXhoqgCQFSN There are other playlists you can view after that.

  • @rastkogojgic699
    @rastkogojgic699 2 года назад

    Why did you wrap the entire function counter with ()? You said it's because of convention, but I tried to do the same example without wrapping everything inside of () and it didn't work.
    It says: Uncaught SyntaxError: Unexpected token ')'
    If I call counter() on the next line it works normally.
    So, the question is, why I can't do it in one line without that additional pair of ()?
    Thanks

    • @AllThingsJavaScript
      @AllThingsJavaScript  2 года назад

      I was doing it as an Immediately invoked function expression. In order to invoke it immediately, you need to enclose it in parens. Otherwise you have to call it on a separate line. A normal function declaration cannot be invoked immediately. Wrapping it in parentheses changes that.

  • @asmartbajan
    @asmartbajan 6 лет назад

    10:25 You say "out of convention" (suggesting they're not necessary), but when I try to immediately invoke a function in JSBin without wrapping it in parens, a syntax error is thrown. Would the code still work with a syntax error? (Still mystified by JavaScript, even though I've been learning it for years! lol)

    • @AllThingsJavaScript
      @AllThingsJavaScript  6 лет назад

      Can you include the code you tried?

    • @asmartbajan
      @asmartbajan 6 лет назад +1

      All Things JavaScript, LLC Thanks for your reply. This version throws an error:
      function () {
      console.log('hello world');
      }();
      while this one works fine:
      (function () {
      console.log('hello world');
      }());
      Cheers

    • @AllThingsJavaScript
      @AllThingsJavaScript  6 лет назад +1

      Wayne,
      You are trying to do an immediately invoked function expression, but you are missing an important piece. There should be parentheses around the function:
      (function() {
      console.log('hello world');
      })();
      Here is a tutorial that focuses on IIFEs: ruclips.net/video/w71IVgfsOL0/видео.html

    • @asmartbajan
      @asmartbajan 6 лет назад

      Yes, I know it's an IIFE I was testing. If you expand my last reply (by clicking "Read more"), you'll see I already did exactly what you did (wrap the function in parentheses) to make it work. The point I was making in my initial comment, was that at 10 minutes and 25 seconds into the video, you said those enclosing parentheses are conventional. Your exact words were, "And just out of convention, meaning it's commonly done when you're immediately invoking a function, I'll put parentheses around it" To me, this implies those parentheses are optional, and not required, to make the function invoke immediately.

    • @AllThingsJavaScript
      @AllThingsJavaScript  6 лет назад +3

      My Bad. It isn't just convention. You must use parentheses or the JavaScript engine misinterprets it purpose.

  • @shawncarpenter5024
    @shawncarpenter5024 6 лет назад

    AAHAAAH!! Thx

  • @laffed2045
    @laffed2045 4 года назад

    but by saying APP.multiplyIt, aren't you calling APP before you call multiplyIT and therefore the execution context is still APP at the point of the call?

    • @AllThingsJavaScript
      @AllThingsJavaScript  4 года назад +1

      The execution context is the APP object, but we still have access to the variable through closure. Does that help?

  • @davidbarrar5968
    @davidbarrar5968 3 года назад

    How come `(() => console.log("hi")());` does not run?
    But this does! (function() {console.log("hi")}());

  • @DominicVictoria
    @DominicVictoria 5 лет назад

    One more question. What is the lifetime of that variable? Why is it still alive after the scope ended?

    • @AllThingsJavaScript
      @AllThingsJavaScript  5 лет назад +1

      That is the essence of closure. It's initial scope has ended, but it was captured by another scope and it will last as long as any scope that has captured it.

  • @zvebrstremnyj6863
    @zvebrstremnyj6863 2 года назад

    Thanks from Ukraine!

  • @muntherjaber9643
    @muntherjaber9643 6 лет назад

    a ha
    thanks

  • @seenuvasanv
    @seenuvasanv 6 лет назад

    Ha ha moment, thanks

  • @stevedoetsch
    @stevedoetsch 3 года назад

    This does NOT explain closures at all. I was surprised to see all the comments from people who said they understood...that's because this only explains scope, not closures!
    You need to be returning functions from other functions to show how closure works.
    See this link instead: ruclips.net/video/1JsJx1x35c0/видео.html
    His IIFE (immediately invoked function expression) is not setup correctly; the close parenthesis should be immediately after the ending bracket, and the result should be stored in a variable: developer.mozilla.org/en-US/docs/Glossary/IIFE
    Why is he declaring a named function and then assigning it to a variable? Don't you declare anonymous functions and put them in variables? And why does he fail to differentiate between declaring a function from calling (running) it? He declares a function and then calls it and says that is an example of closure when it's not.

    • @AllThingsJavaScript
      @AllThingsJavaScript  3 года назад

      Duke, returning a function from another function that has access to it's parent scope (lexical scope) is an application of closures. It is not what a closure is. A function that has access to its parent scope is a result of closure and that can happen in several different situations. To emphasize this point here is a question: How does the function have access to the count variable if it is not through closure? (The definitions of closure are shown at 4:30.) Also, there are two ways to declare IIFEs. The way you describe and the way I show here, which I prefer. I explain the difference in my tutorial on IIFEs. Finally, you can always assign a function a name. Even when it is a function expression. Not commonly used, but it is available.

  • @noname-zj6qg
    @noname-zj6qg 4 года назад

    youtube remove dislike button.

  • @benzflynn
    @benzflynn 4 года назад

    Hey Buddy - some stupid coding there.
    *var sumIt = function sumIt() { ...}* should be *var sumIt = function() {...}*
    *var APP = (function module() {..}* should be *var APP = (function() {...}*

    • @AllThingsJavaScript
      @AllThingsJavaScript  4 года назад

      You can name your functions if you choose to. That is the only difference. I'm not sure what is stupid about that. Yes, more to type, but at times it can be very helpful in debugging.

    • @benzflynn
      @benzflynn 4 года назад

      @@AllThingsJavaScript But isn't it already named by its function var declaration ? If there's some error in it won't the JS console reference it as APP.sumIt() ?

    • @AllThingsJavaScript
      @AllThingsJavaScript  4 года назад

      So the var declaration is simply the variable that references the function. On the console things will show up, but in a debugger you may want to name the function. When you declare a function using a function declaration, the function is named. But when you declare a function using a function expression (like the example here) the variable references the function, but it doesn't have a name. So at times you may want to give it a name for debugging. That may have been what I was doing in this case. I don't always use a name in this situation but maybe I did some debugging on that code before showing it. I don't remember for certain.

    • @benzflynn
      @benzflynn 4 года назад +1

      @@AllThingsJavaScript I see. I gotta say thanks for getting these modules across. My old website calendar had way too many global vars, then you have slide- or video shows, SPA page switches, hamburgers, testimonial displays, etc. Just too many global vars on the same JS file. More organized now.