Programming Terms: Closures - How to Use Them and Why They Are Useful

Поделиться
HTML-код
  • Опубликовано: 7 мар 2016
  • In this programming terms video, we will be looking at the term "Closure". We will learn what a closure is and why they are useful. We will look at examples in both Python and JavaScript. In Python, understanding closures helps us understand common language features like decorators. And in JavaScript, closures will allow us to better understand callback functions and much more. Let's get started...
    The code from this video can be found at:
    github.com/CoreyMSchafer/code...
    ✅ Support My Channel Through Patreon:
    / coreyms
    ✅ Become a Channel Member:
    / @coreyms
    ✅ One-Time Contribution Through PayPal:
    goo.gl/649HFY
    ✅ Cryptocurrency Donations:
    Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
    Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
    Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
    ✅ Corey's Public Amazon Wishlist
    a.co/inIyro1
    ✅ Equipment I Use and Books I Recommend:
    www.amazon.com/shop/coreyschafer
    ▶️ You Can Find Me On:
    My Website - coreyms.com/
    My Second Channel - / coreymschafer
    Facebook - / coreymschafer
    Twitter - / coreymschafer
    Instagram - / coreymschafer

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

  • @riverland0072
    @riverland0072 4 года назад +441

    "Therefore, in simple terms: A closure is an inner function that remembers and has access to variables in the local scope in which it was created even after the outer function has finished executing"... It is absolutely impossible for this guy not to make heaven

    • @user-zo2ky4mz7d
      @user-zo2ky4mz7d 4 года назад +11

      He is a fantastic teacher no doubt 👌🏽

    • @souranumaji4213
      @souranumaji4213 3 года назад +10

      No one knows how to teach a complicated topic better than him

    • @treyheaney9483
      @treyheaney9483 3 года назад +3

      no it's not

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

      You got it fam

    • @nirajraut9408
      @nirajraut9408 2 года назад +2

      @@treyheaney9483 Why? Could you please explain?

  • @kickbuttowsk2i
    @kickbuttowsk2i 4 года назад +53

    okay, let's watch the decorators video at last. You rock, Corey.

  • @satoshinakamoto171
    @satoshinakamoto171 4 года назад +54

    i dont think people say this enough, but your channel is probably one of the most valuable programming tutorial channels in YT. i keep learning from this channel and i all i can give is my appreciation.
    thank you.

    • @dineshraj78
      @dineshraj78 9 месяцев назад

      true, i felt the same! great help!

  • @varunkumar_vk
    @varunkumar_vk 4 года назад +40

    "My hope here is that, by seeing this in two different languages, it will really knock home the concept, rather than just the syntax of the language". Absolute brilliance!

  • @supermariosunshine64
    @supermariosunshine64 6 лет назад +139

    So, if I got it right, closures are when a function remembers the environment it was created it, specifically the variables around it.

    • @coreyms
      @coreyms  6 лет назад +60

      Yes, that is a good concise description.

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

      Thanks you just nailed it 😇

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

      You nailed it almost 3 years ago😂

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

      Looks like normal human childrens behaviour to remember which city 🏙️ born

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

      Some clarify me with another example - So that I will get it 100% please....

  • @ossenaar
    @ossenaar 6 лет назад +70

    Best (Python) teacher who explain concepts easily and clear. As a beginner programmer, I read and study Python concepts in books and jupyter notebook samples. But, for certain concepts, I need additional visual explanations and Corey's videos always help me out greatly! In eBooks, I always highlight important concepts with a note link to his RUclips video to revisit the videos later.

  • @mijaelwatts
    @mijaelwatts 6 лет назад +31

    Man, I tried to learn Closures last year and failed miserably. Today I gave it another try(this time with ur video) and now I totally get it. Thank you very much man. God Bless!!!

  • @Max-my6rk
    @Max-my6rk 6 лет назад +83

    Thanks very much. This is the only video explaining Closures the way it should be.... very clear and easy to understand! U r truly awesome!

  • @souranumaji4213
    @souranumaji4213 3 года назад +7

    Video on "First Class Functions" is the base. Once you clear that idea, understanding closure becomes much easier... Corey you are genuine and genius teacher, a teacher everyone deserves to have at least once in their life.

  • @nicholaszustak768
    @nicholaszustak768 6 лет назад +5

    Completely forgot these from my classes; this video helped me remember and learn it way more in depth! Thank you

  • @oregonbry
    @oregonbry 6 лет назад +5

    Thank you! After all these years, I feel like I am finally starting to understand Closures. Awesome!

  • @santoshkc1922
    @santoshkc1922 4 года назад +10

    You are the only person who can make me understand Python!!! Your excellent methodology of making the concepts clear and those top notch examples gives a break through to any person willing to learn the language. Thank you a lott!! God bless you

  • @BusinessDevelopmentSolution
    @BusinessDevelopmentSolution Год назад +2

    I have no words to thank you because this was a very tricky concept that I was trying to learn for last 2 days in dart and your video make me able to understand what exactly closure does, thank you so much

  • @DanCanning
    @DanCanning 5 лет назад +8

    Never mind first class functions. This was a first class explanation. You closed off my confusion nicely. :)

  • @ratonmagico
    @ratonmagico 5 лет назад +3

    When I'm coding in Python and come across with something I don't know or I don't remember quite well I come back to your videos. So clear and insightful at the same time!

  • @RalphAlberg
    @RalphAlberg 3 года назад +6

    Corey's videos are always excellent - his explanations are clear and he makes complex topics very accessible. Thank you!

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

    4:36 That's what a close it. I am yet to complete watching video. But just the way you put forward these concepts, always keeps me going through your videos. Thank you sir.

  • @pumpkinking715
    @pumpkinking715 8 лет назад +6

    Great video! I really liked the examples you used. They really helped to demonstrate actual use cases for closures. I am looking forward to the python decorator tutorial

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

    I get it finally, a closure is a inner function that has access to variables within the local scope even after the outer function has finish executing.
    Thanks a lot and keep up the good work!

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

    Another great video. This was one of the hardest subjects for me and I understood it very well. Thank you Corey.

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

    I absolutely love it that you demonstrate the concept in two different languages

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

    after a few RUclips vids and reading a couple of Python books, i finally found someone who explains Closures and Decorators to a level that helps me to completely understand them and their uses. thanks for your efforts Corey

  • @gatsby335
    @gatsby335 3 года назад +14

    I am here from the *Decorators!*

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

    I like the way you explain complex topics in a easy way.

  • @JG-mw7yd
    @JG-mw7yd 4 года назад +4

    Hey Corey, recently stumbled on your videos and I'm so happy I did, thanks for taking the time to make such great tutorial videos!
    Also, for those with slower auditory processing like me, set the playback to 0.75 speed, it is perfect!

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

    Excellent video, Corey. Explanation is concise and the code snippets effectively demonstrate the the concepts of closures.

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

    Wow man, the teaching skills that you possess is unmatchable

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

    Thank you for this explanation! Great approach in making the video language agnostic. I came across this topic in studying Dart with Flutter where closures and anonymous functions are used frequently and this made things clear.

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

    Man, thank you! Googled everywhere with no luck and finally found you and understood closures ;)

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

    Very helpful concretization of a pretty abstract term, thanks!

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

    Another great video. Though a complicated topic. I understand how they work from your examples, but I'd like to know more about when and why we would need to use these. It's one thing to understand how these things work technically, but its another leap in understanding to know when and why to use a certain approach to solve a problem.

  • @user-lf1br3pf6m
    @user-lf1br3pf6m 6 лет назад +1

    Those are 3 great examples. And I like your explanation where you say that a closure encloses the outer free variables inside the inner function (paraphrasing).

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

    Thank you for making these wonderful videos! They're really helpful when I tried to understand these concepts!

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

    Amazing explanation. Having read and seen other explanations, can vouch for this one as being the one that I found understandable.

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

    I really like the way you represent all those things in very easy manner

  • @scuti7073
    @scuti7073 Год назад +1

    free variable is the variable that is not defined within the inner function but is defined in the enclosing function. It can still be accessed in the enclosed function.
    "A closure is an inner function that remembers and have memory of the variables from the local scope from which it was created created (this includes arguments passed to the parent function)- even after the outer function has finished executing"- 4:50
    A closure closes over the free variables from their environment- defined outside of the function/

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

    dude this is actually crazy how easy it gets when you understand it
    Thank you.

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

    Really great video man. Helped it click for me with deeper understanding where other videos couldn’t. Thanks!

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

    Good job! Simple and precise ... Thanks!

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

    I spent the entire day trying to figure out what closure and failed miserably, and then this guys clears it up in 5 minutes. Great job, man, thank you a lot.

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

    I have recommended your channel to a lot of my colleagues over the years

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

    Thanks Corey. Nobody can explain this the way you do.

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

    Great video, well explained with good examples. :)

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

    I really like this example...thank you very much

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

    You are the best, I have been following your channel for years, and I always come back to your videos.

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

    Wow. Couldn't understand better than after watching this great video!

  • @chronicfantastic
    @chronicfantastic 8 лет назад +2

    Your videos are fantastic, thanks a lot.

  • @Dj.julien.b
    @Dj.julien.b 5 лет назад +1

    Very useful ! I love your videos I learn so fast! :) thank you for making this golden content you provide :)

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

    Thanks, very good explanation!

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

    Awesome tutorials. The greatest Python teacher i must say

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

    Outstanding! Thank you so much!

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

    Really nice video. Very well explained.

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

    well explained and easy to understand for beginners

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

    Brilliant selection of examples, you made me understand! Now I feel I am evolved!

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

    Superb Video sir .. Thanks for explaining the wiki's definition with an example .. Really helped me :)

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

    super cool video, finally understood closures :)

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

    Thank you for the video. I am grateful for your time and contribution. Kind regards, Akira.

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

    Your explanations and video quality are top notch

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

    Amazing Explanation bro

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

    cheers mate, helped out a lot

  • @alejandronieto576
    @alejandronieto576 2 месяца назад

    Great video. Thanks a lot from Argentina.

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

    Thank you! You are a great teacher!

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

    Thanks so much for your efforts

  • @bErKcorner
    @bErKcorner Год назад +1

    The way I prefer to remember this concept:
    The outer function "closes over" an inner function, therefore it's a closure. While doing so, it "injects" its local scope into the function being closed. So the function that is returned will be executed with the injected state every time it is called.

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

    Top Video,really focuses on understanding.

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

    You are the best teacher I've seen

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

    one of the best videos on closures. CLEAN and CONSICE. keep up the good work +Corey Schafer (y)
    I have one request, can you do a video on "Variable bindings (early vs late binding) in python" Thanks!

  • @timmyl9361
    @timmyl9361 9 дней назад

    Thnx dude. This is all I needed to understand it

  • @Jo-id9zm
    @Jo-id9zm 7 лет назад

    Thanks a lot, man! Very useful.

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

    Another great video! Thanks again.

  • @IrshadKhan-vk8rn
    @IrshadKhan-vk8rn 3 года назад

    All My interview for The MNC interviewer ask what is closure i explained all as i remembers and finally i am all in previous year. Even Interviewer Knows About You Corey and we discuss how awesome your videos are ...:-) Currently working there have been 1 year and in core development team thanks corey again.

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

    Thanks for your effort

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

    Thanks was very very helpful.

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

    Hi Corey, I really like your videos. You explain everything in a very elaborated manner and that too with practical examples which helps in getting deeper insights and developing intuition.Keep the good work up.
    Also, Please upload more videos of Bronx, haven't seen his new videos.PS-> his expression in running late video still makes me smile( I've watched it multiple times). :-) :-)

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

      Haha, will do!

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

    thanks well explained brother

  • @Colstonewall
    @Colstonewall 8 лет назад

    Enjoyed it, thanks.

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

    Thanks for another great video that explains the mechanics, not just syntax. What I would like to understand better: What are real world use cases in which to use closures. Or in other words: In my problem solving efforts before writing code, what are patterns that call for closures.

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

    Every video, got to watch another video. This is an endless while loop

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

    Good as always. Thanks.

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

    This video made it click, thank you!

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

    great explanation thanks you

  • @maltepedersen9180
    @maltepedersen9180 5 лет назад +3

    Brilliant! It finally starts to make sense, what closures actually are :) Thank you, for a very pleasant and informative video.

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

    Thank you!

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

    The amount of function passing in the last example was nuts haha.
    it took me writing the code out and writing my own comments plus reading out loud to fully follow the logic here.
    so if I understand it correctly - add_logger = logger(add) takes the add function (NOT EXECUTED) as a parameter to the logger function (which also just passed the function without executing it). Since the logger function was called using the brackets "()" it was executed and returned the inner function (log_func) because of the return log_func at the end of the logger function. But because of closures it remembered that you passed in the add function. So when you executed add_logger(3, 3) it passed the add function into the log_func and executed the add function with the supplied arguments within the print function.
    just wow - that is a brain twister.

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

    awesome stuff... thanks dude

  • @jasonreviews
    @jasonreviews 8 лет назад

    Good stuff!

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

    Hi Mr. Corey, Please make videos for data structures and algorithms using Python. Its hard finding tutorials for DSA in python. I believe i can understand the concepts easily if you teach the DSA.

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

    Great explainer

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

    Such a helpful video! Here's a heuristic I used to help understand why we need to set my_func = outer_func() in order to execute the inner function instead of just calling outer_func().
    outer_func() (in the second example where we return inner_func instead of inner_func()) returns, but does not execute a function. If you want to execute it, you might want to call outer_func()() but that syntax is illegal, so we set outer_func() to the variable name my_func so we can call my_func() with just one set of parentheses. Thinking of an illegal function with double parentheses and re-writing it using legal syntax helps me conceptualize why we use my_func.

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

    Great video :)

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

    thank you! thank you!

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

    Extremely well-explained tutorial, but I still can't figure out why I would ever want to use this..

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

      His last example with the logging is a good example, though as he says, decorator would be the more pythonic way (although it's still using a closure as well). The way that he's using the logging wrapped around the other two functions, add and subtract, show how you can apply logging to any arbitrary function in your application without having to replicate all of the logging machinery in every function. It makes your code way more compact and also far more maintainable.

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

    beautiful!!

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

    My Savior...Thaaanks so much for this simplicity...

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

    Awesome!

  • @stephenpaek9175
    @stephenpaek9175 5 месяцев назад

    Excellent

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

    I owe you so much as I learnt most of my python from you.
    I just got confused between firstclass function videos and closure video.
    Just to confirm,
    Do you mean if I assign function to variable like you did in first video. It means first class function.
    whereas if you function takes function as argument but returns function with parenthesis which can be executed later and it remembers the value of variable than its called higher order function.
    and closure is where you take function as argument to other function which returns some inner function.
    Please pardon me if I sound stupid here... :)

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

    no one can explain like him

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

    Thank you for all the series you have you are such a great teacher! I do have one question on this video. The last example when you are doing the logger example withing the file you create with the example it looks as so:
    INFO:root:Running "add" with arguments (3,3)
    ok so I understand From running on but INFO:root where is that coming from and what is the significance of them?

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

    Hi Corey, Thanks for the great video.
    I've a qiuck question, how to call them, if there are two or more inner functions?