Closure exposure therapy - Exploring closures in JavaScript with friendly live mob programming

Поділитися
Вставка
  • Опубліковано 3 жов 2024

КОМЕНТАРІ • 110

  • @funfunfunction
    @funfunfunction  5 років тому +19

    Jump to
    06:22 What are closures?
    09:00 Are functions hoisted to the top of their closure?
    18:10 Closures are referenced, not copied
    20:00 Object Orientation and closures and classes
    34:30 Where do you use closures / Dependency Injection

    • @NovaChan07
      @NovaChan07 5 років тому +2

      Fun Fun Function thanks for doing the extra work of providing an intro and linking to segments. It makes such a difference!

  • @vitorvitali
    @vitorvitali 5 років тому +35

    please keep doing videos like this, they are so much better

    • @funfunfunction
      @funfunfunction  5 років тому +2

      Hi VB! Thanks! But "videos like this" can mean many things to me - can you specify some aspects of the video that you like?

    • @vitorvitali
      @vitorvitali 5 років тому +5

      @@funfunfunction oh sure, i meant like going deep into a single topic. :)

    • @foxfrito
      @foxfrito 5 років тому

      @@vitorvitali I agree! ;)

    • @dunteman_racing
      @dunteman_racing 5 років тому

      @@funfunfunction I have to agree with this. Your earlier video's really helped me jump-start my confidence in JavaScript development by diving deep into the design, behavior, and gotchas with different features of JavaScript. Highlighting errors in lexical scoping, hoisting, etc. I particularly like your examples that twist the mind a little, not only in trying to understand the behavior of what you are coding, but also applying them to real world examples. The best example that this video brings to mind was your use of Currying in your initial genericFunction. If I hadn't watched your earlier videos on Currying, I would have been quite confused watching you use it here in the context of closures (also a great video series of yours). I've been doing JavaScript development professionally for a few years now, but it was your videos that introduced me to many new and difficult to understand areas of JavaScript that I would not have come across in the normal requirements of my Job.
      When you can stop asking "why" when learning a new topic, instead of just accepting that is the way something is, you fully understand it. That is powerful to personal development because you can take that knowledge/experience, especially in programming, and use it to learn something new that may be related. Then on and on and on to the next topic.
      Just my feedback to your request to expand on "videos like this"

  • @incubated
    @incubated 5 років тому +8

    function declarations are fully hoisted. function expressions are hoisted by assignment. that's why you can invoke the function before its declaration, but returning it turns it into an expression, so the assignment is not hoisted. if you were to write let func = function(), only the func name would be hoisted, but the assignment won't happen until the interpreter reaches line number

    • @dealloc
      @dealloc 5 років тому +5

      A note is that while let/const are hoisted, they are also initialized differently from var.
      Using var will initialize the variable _before_ the line is executed, but can still be accessed, although the value will be undefined, until it is executed. Whereas let/const are initialized when the line that it's at is executed. That means any reference to the let/const declaration, before their initialization, will be in the Temporal Dead Zone and cause a Reference Error.

  • @lenaggar
    @lenaggar 5 років тому +1

    I love this format of videos .. kind of reminds me of your old videos when I was in my first steps in web development .. you helped me immensely

  • @danielsimionescu298
    @danielsimionescu298 5 років тому +10

    Is this the return of functional JS videos? 😆

    • @iorbit
      @iorbit 5 років тому

      Yes Please!

  • @realchrishawkes
    @realchrishawkes 5 років тому +2

    When are you going to try to take this full-time? Good video!

  • @funfunfunction
    @funfunfunction  5 років тому

    Patrons! 💛Any feedback, questions and musings regarding this week's show that you would like to share in private, here is the link to the topic on the Fun Fun Forum: www.funfunforum.com/t/episode-feedback-and-questions-closure-exposure-therapy/8527

  • @muzafferckay2609
    @muzafferckay2609 3 роки тому +1

    If you return an object which includes some functions from factory function then you should define that functions in returning object to avoid created each time the factory function invoked.

  • @TheAcidMotion
    @TheAcidMotion 5 років тому +1

    JavaScript Hoisting isn't an actual thing, it is just an 'easier 'way to explain what happens but i found it to be a pretty bad practice when teaching people JS.
    For anyone interested in why we teach "Hoisting" even if it doesn't really exist in a way we define it please check out Kyle Simpson's take on this.
    frontendmasters.com/courses/javascript-foundations/hoisting/
    I couldn't recommend enough books Kyle S. wrote as a 'Must read'.

  • @generationwolves
    @generationwolves 3 роки тому

    Classes offer a slightly better performance advantage when multiple instances of the object needs to be created. Classes create one blueprint in memory that all instances will share, while closures create a fresh reference in memory for every instance.
    Closures are a better fit for simplistic implementations as they are easy to write, and do not use the 'this' keyword. Closures can also be preferred if multiple instances of the object is not required, and encapsulation is important.

  • @fcs_96
    @fcs_96 5 років тому

    Really like your channel! I'm definitely subscribing to your channel. It's filled with lots of useful information about JavaScript. I like JavaScript and you make it explain and teach the topics more clearly with your great teaching style. I look forward to working on more JavaScript projects and to add to my channel now that I understand the language and concepts more deeply. Thanks!

  • @funfunfunction
    @funfunfunction  5 років тому +1

    NordVPN (Sponsor)
    nordvpn.org/funfunfunction
    Coupon code: funfunfunction (Use to get 1 extra month when signing up for the 3-year plan, which also gives 75% off)

    • @funfunfunction
      @funfunfunction  5 років тому

      Hey Alexandre!
      Fair question.
      The way I see it - KNOW is generally hard, for anything. There are very few certainties in life - you don't actually know if your heart is going to beat one more time. BUT we can make reasonable, educated guesses of probability by analysing the context.
      This is how I think about it:
      I want to use *SOME* VPN as my traffic is unprotected from eager government mittens otherwise, the question is which one.
      There are a couple of indicators why I'm willing to trust that NordVPN not to store my own traffic (and why I'm willing to also recommend them to you):
      0. Single-product company. NordVPN has no other products, no other service, than secrecy. If their reputation around that falls, the whole company falls and everyone loses their jobs. That's an extremely strong incentive to not only to not sell your data, but also to protect no-logs with tooth and nail because it's their very lifeblood.
      1. Incorporated in Panama (EU and US mandates all companies under their domain to store traffic)
      2. Not a budget option - quality product (if I wanted to be a honeypot that resells sensitive data, I'd set my price to free to cast a wider net)
      3. They hire independent auditors check that they are not storing traffic (nordvpn.com/blog/nordvpn-audit/)
      4. Have been operating for six years (nordvpn.com/about-us/) and still has a good reputation from what I gather from around the web.
      Does that make sense?

  • @ШамильДжакеев
    @ШамильДжакеев 5 років тому

    Когда программист такого уровня, с таким огромный багажом знаний, не может отключить построчно линтер, а так же не понимает почему не происходит поднятие (hoisting) - это вселяет надежду в свои силы 😀😉.
    Thanks MPJ!

  • @ViniciusRocha-bl1lk
    @ViniciusRocha-bl1lk 5 років тому

    I love this type of video, like your first ones. THANKS!!

  • @dimaorols8143
    @dimaorols8143 5 років тому

    Every mutable property on the window object is a closure relative to declared functions in the main context.

  • @JamesGaehring
    @JamesGaehring 5 років тому +3

    Really like this style of live-stream, something nice to break up all the "fail together" vids

  • @vlad981
    @vlad981 5 років тому

    About performance closures vs prototype: recent version of v8 doing optimization, so difference in terms of speed is 10-20%. You can google JS-perf and test it by yourself.
    That's another reason why you should write idiomatic JS, and not try to replace compiler. We've seen it for forEach vs for, string concatenation etc.

  • @mauricioberlanga
    @mauricioberlanga 5 років тому +4

    Please do an episode on Observables!

    • @mauricioberlanga
      @mauricioberlanga 5 років тому

      Or a complete series :D

    • @qwarlockz8017
      @qwarlockz8017 5 років тому +1

      I second that. I use them and have for a long time but... man EVERYTHING from Java Spring to React to Angular2 seems at its base extensions of observables. Even the messaging systems that are popular now like RabbitMQ!

  • @Fernando-ry5qt
    @Fernando-ry5qt 5 років тому +1

    You should do a video about advanced closure applications, like trampolines, it is an amazing optimization for recursive aplications, using the power of closures to avoid stack overflows.
    Functional programming is awesome.

  • @boomer5015
    @boomer5015 5 років тому

    I realised I don't know Closures well enough as I don't use them often enough. I keep forgetting that the parent object creation args are accessible to method bodies returned as an object. It always seems black magic as there's no const/let defined. I need to use dependency injection more to reinforce the power of closures.

  • @cerdarius
    @cerdarius 4 роки тому

    Seems like the same deal with NordVPN is available without the funfunfunction coupon...hhmmm...

  • @shivangchaturvedi237
    @shivangchaturvedi237 3 роки тому

    What is your take on TypeScript? It must be a JS delight for JAVA devs and you must loathe it to your guts? lol

  • @akashprasad3604
    @akashprasad3604 5 років тому

    function Declarations are hoisted not expressions

  • @BocaR1
    @BocaR1 5 років тому +1

    Alrighty...that last part made me re-think my comfort with closures

  • @arvindvs8934
    @arvindvs8934 3 роки тому

    What’s that he is sipping on? I feel like having a 🥃 while watching this video 😀

  • @nathancornwell1455
    @nathancornwell1455 4 роки тому

    Everyone should be using TOR

  • @nathancornwell1455
    @nathancornwell1455 4 роки тому

    Any time i can avoid using the word "this" , is a win in my book . Drives me crazy there isn't more tutorials on functional style programming and almost all of them are OOP exclusively.

    • @nathancornwell1455
      @nathancornwell1455 4 роки тому

      Also, at the 28:00 you would have to use bind() if you didn't/can't use arrow functions .

  • @lnr124
    @lnr124 5 років тому

    I still have no idea why you don't like classes and your slight segway into it didn't really answer anything? It seems you just don't like it because it's just a veil overtop of actual prototyping?

    • @funfunfunction
      @funfunfunction  5 років тому +1

      It's not that I dislike them per se, I just like the simplicity and elegance of just using closures and don't know why people are so hell bent on using classes when we have this beautiful construct that does the same thing without any of the drawbacks of classes.

  • @michalbotor
    @michalbotor 5 років тому +1

    diss closure disclosure!

  • @guilebas
    @guilebas 5 років тому +1

    Hi mpj, Kyle Simpson (the author of "You don't know JS" and "Functional Light JS" books) uses a koan coined by Anton van Straaten to introduce/illustrate differences between objects (and classes) vs closures: "objects are poor man closures, and vice-versa" (tldr). Objects have structure and state that is mutable, and that might be considered as an advantage. Anyway, you asked for comments and this koan helped me a lot (as well as some of your first UA-cam videos).
    people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html

    • @funfunfunction
      @funfunfunction  5 років тому +1

      Kyle 💛

    • @guilebas
      @guilebas 5 років тому +1

      I forgot to express the same 💛 for his work in my comment. :)

  • @KrotUA
    @KrotUA 5 років тому

    Hi, thanks for this video I really liked it. What extensions are you use, especially last two looks very interesting.

  • @owen19901
    @owen19901 5 років тому

    Great Job @Fun Fun Function i enjoy this types of videos:)
    closures are great if you get some concepts of functional programming :) then the moment comes "AHAAA" and composing the function is a pleasure. And I also think that although JS is object-oriented, it is a style of writing code closer to it for functional programming.

  • @Kenbomp
    @Kenbomp 5 років тому

    Props for talking about it, closures have been around since the sixties and implement in the 80s on small talk. Haters are talking crap. Think of it as local git for variable. They are important when your code scales beyond single cpu apps. See also snap Berkeley the jscript langauge of scratch which uses closures.

  • @EranBarOz
    @EranBarOz 5 років тому

    I'm sorry if I'm repeating someone cause I didn't read all the comments and watched only the first 10 minutes so far. And what I want to say is that when you return a function (){} instead of a name of function that declared earlier I think that you creating a new insurance of that function every return

  • @qwarlockz8017
    @qwarlockz8017 5 років тому

    Thank you so much MPJ. I have heard about and even used closures for a while now but did not really get it. This really helped get at least a piece of it. I do have to say the sexiest and most... oooo not sure I can do that... was your refactor at the end moving from the function notation that is verbose but easy to understand to the arrow notation that is so concise and clean and yet... hard to understand what it is doing when you look at it. Often on those I go back to rewrite in function notation in order to see what it is actually doing. But boy it does look pretty!

  • @FPCScreative
    @FPCScreative 5 років тому

    I know I'm late to this, but you were looking for "// eslint-disable-next-line [param]".

  • @truongvo7466
    @truongvo7466 5 років тому

    Thanks for this video I really liked it. What extension are you use? It shows results without debugging...

  • @rameshh.b523
    @rameshh.b523 5 років тому

    can somebody explain the difference b/w closure and inner function

  • @RogueAfterlife
    @RogueAfterlife 5 років тому

    I felt the part about trying to remember the eslint disable comment

  • @lixler9219
    @lixler9219 5 років тому

    Your a smart dude that I just randomly followed off a "shameless plug" (your words ) on quora, 10 people said what you said in that post, but you were the only one I gained knowelege from cause you just kinda said it how it was, and everyone else was just like pretending to be smart only because they knew words. And when you called node a thingamabob in that post, it put a good ass smile on my face to know good smart people still exist. The way you put it, by throwing that little bit of goof in the knowelege, it clicked way better in my head than when the other people called it an interpreter, just to look good, they didn't want to teach. But I've only been playing with JavaScript and API's for like 3 days now, so like I'm the newest of the newest. I'm just a lazy 18 year old kid, but I hope it can make you feel good to know that I genuinely want to sit down and watch your whole channel, learn anything I can, learn everything you have for me, just after seeing 10 mins of this video and reading your 2 year old answer on a 5 year old question. I wish I could meet people like you in real life, in person. Your a special kinda human, special in a legitimately good way, unlike these people I'm forced to live around who are special, but in bad ways I want nothing to do with. I hope your gonna read this and feel what I felt in that moment. I would really like to talk to you some day.

    • @lixler9219
      @lixler9219 5 років тому

      And like how do you manage to be so woke, without looking batshit crazy? You got some of the smoothest woke stuff coming out, and that's REALLY hard to accomplish

    • @funfunfunction
      @funfunfunction  5 років тому +1

      Hah, this was one very authentic comment that moved me a lot for some reason. Thank you so much for writing this, made my day! 💛
      As for woke, I'm not totally sure what the word means, I guess that means I'm getting old. Maybe it is because I care about correctness a lot, think about things a lot in order to develop a clear view, and I care more about expressing my views correctly than being liked. But who the hell knows, maybe I just say things you agree with? :)

    • @lixler9219
      @lixler9219 5 років тому

      @@funfunfunction Just dont google the word.. lol its so wrong. Its the wrong word for what i mean, kinda

  • @shashikumar-zc8gd
    @shashikumar-zc8gd 4 роки тому

    use CTRL+ to zoom in and CTRL- to zoom out i hope you know already

  • @JPCase104
    @JPCase104 5 років тому

    Can someone explain to me how the flow on the example at ~~41:00 works?

  • @joebazooks
    @joebazooks 5 років тому +1

    im pretty sure all `functions` simply have access to the level above them. thats it

  • @iorbit
    @iorbit 5 років тому

    Ive been coding professionally for 3 years and have never really understood the concept of closures.

  • @inaccessiblecardinal9352
    @inaccessiblecardinal9352 5 років тому

    You're returning the innerfuct. If you just declare it, it's hoisted.

  • @this.channel
    @this.channel 5 років тому

    This video addresses some of the issues I have learning JS. Thanks

  • @sultanb6685
    @sultanb6685 5 років тому

    Can someone explain the point of the process at 41:30 and forward?

    • @funfunfunction
      @funfunfunction  5 років тому

      What the point of dependency injection is? Check out my vids on it here. ua-cam.com/video/0X1Ns2NRfks/v-deo.html

  • @rockywang4909
    @rockywang4909 5 років тому +1

    This video could have been shorter.

  • @osamatalaat8113
    @osamatalaat8113 5 років тому

    mpj ❤🌸
    i think now with es2019 we can use private members in classes by adding # before the name of the member. i think now you can say this.#food

    • @osamatalaat8113
      @osamatalaat8113 5 років тому +1

      i paused the video to tell about the private members and you already told about it. i have no patience hhhhhh

  • @lenaggar
    @lenaggar 5 років тому

    I love you mpj, but you really need to work on your typing-while-live skill :D

  • @Ali-M93
    @Ali-M93 5 років тому

    More JS videos please!

  • @IhsanMujdeci
    @IhsanMujdeci 5 років тому

    How did he get the "//?" to reveal properties of variables?

    • @qwarlockz8017
      @qwarlockz8017 5 років тому +1

      Quaka? Is that how you spell it? It is a plugin for Atom and Visual Studio

    • @funfunfunction
      @funfunfunction  5 років тому +1

      quokka.funfunfunction.com

  • @Lbmaniak
    @Lbmaniak 5 років тому

    Thx for video.

  • @mohamadtajjiou7508
    @mohamadtajjiou7508 5 років тому

    thank you

  • @Dr3amDisturb3r
    @Dr3amDisturb3r 5 років тому

    Wait, so closures are not so good for memory optimization, because functions are re-created every time, but classes recreate them under the hood as well?
    Can someone explain please?

    • @funfunfunction
      @funfunfunction  5 років тому +2

      Classes don't do that per default, but if you place .bind everywhere, use the class arrow function magic (which binds under the hood) and other funkyness then yeah, classes do recreate a lot of functions.

    • @Dr3amDisturb3r
      @Dr3amDisturb3r 5 років тому

      @@funfunfunction So the class is not so classy then haha, Thanks for the reply MPJ :)

  • @Lbmaniak
    @Lbmaniak 5 років тому

    Thx for video.

  • @andrzejaa
    @andrzejaa 5 років тому

    Refactoring with WebStorm is much easier ;)

    • @funfunfunction
      @funfunfunction  5 років тому

      Haha, took me years to wane myself off my ReSharper addiction. :) I'm back to doing things manually nowadays.

  • @Abmallim
    @Abmallim 5 років тому

    the most confusing this for me was double arrow functions

    • @funfunfunction
      @funfunfunction  5 років тому

      Ah, for sure, should have spent more time on that. It is exactly the same thing, but shorter, but I could have transitioned with more care there, and left the old code commented out.

  • @katywings
    @katywings 5 років тому

    Dont getting the argument why I should use closure "classes" instead of the prototype, if one of ten class members needs the bind. In my opinion the functional vs oop discussion in js often feels really "empty" or should I say religious. Anyone knows something you can do with closure classes and you cant do with prototype classes? Sure you dont need the "new" keyword for prototype classes, but even this argument is so fictional. I really would like reasons that I can give my juniors without sounding like a priest. As much as it didnt sound like it, but I actually love functional js xD.

    • @funfunfunction
      @funfunfunction  5 років тому

      But why not use the closure instead of class? It's not religion, I'm just providing the case that this is a valid way of doing things with that has certain benefits, not that classes are invalid. I'm merely saying that the case isn't so clear cut for classes. If anything, I'm the opposite of religious.

    • @katywings
      @katywings 5 років тому

      @@funfunfunction
      Didnt wanted to sound like I am directly targeting you with my comment and I hope you didnt take it personally, but sorry otherwise ;). It was my general oppinion on this topic not specifically on your video.
      About your question, regarding why not just using closures then, I cannot answer this question without knowing about which use case we are talking about. Both have their own, in my oppinion small differences that make them favorable for certain situations, but if I would have used a realworld comparison Pepsi vs Cola comes to my mind xD.
      The point that I wanted to make is, that still to this moment I never heard of anything that you can do with protoClasses/closureClasses that you cant do with the other one, and because of this, the whole topic feels to me so religious I guess. Do you know of something (except proto memory optimizations) that only one of them can do? (Again this is just a question, I dont want to offend you and I find your channel very valuable and often recommend it)

    • @funfunfunction
      @funfunfunction  5 років тому

      For me I'm not particularly interested in It's not about functionality, it's about simplicity. The class / prototype adds a kabillion moving parts and a closure is such a simple construct that I feel is discounted for no good reason.

    • @lunify2814
      @lunify2814 5 років тому +1

      When you use object oriented programming you opt into the dynamic binding (OOP's idea is the usage of `this`) as opposed to lexical scoping. If you don't need dynamic binding, why create it in the first place, or worse, try to simulate lexical scoping by using binds throughout your code ?
      It all comes down to using the right tool for the job

    • @katywings
      @katywings 5 років тому

      @@lunify2814 Yeah +1 :).
      Currently I choose between Classes and Closures kinda this way (but its not written in stone :D), those are just indicators:
      - Will the structure be used for list items of very large lists and is there a high memory use potential? "Classes"
      - Does the use case need inheritance? (usually not ;)) "Classes"
      - Is ducktyping not possible with the desired structure / is there need for instanceof checks? "Classes"
      - Is it part of a library and is there a chance it will be used for list items? "Classes"
      - Is the structure only used as a container for event handlers? "Closures"
      All other cases "closures"

  • @eniolaajiboye4399
    @eniolaajiboye4399 5 років тому

    yessss! this is the content i subscribed to years ago!!!

    • @funfunfunction
      @funfunfunction  5 років тому

      What kind of content made you subscribe? This is a completely new format so I'd love to know what it is you feel it shares with old material.

    • @eniolaajiboye4399
      @eniolaajiboye4399 5 років тому

      @@funfunfunction i kind of posted that video before even completing the intro. It turned out to be slightly different from what i expected lol. But it was still amazing to watch and i learnt quite a bit.
      I found your channel in 2016 and it really helped me level up by introducing concepts and explaining not just how they work but also some of the gotchas. I always recommend your channel to friends who have been writing JS for at least 6 months for the same reason.
      I really enjoyed the FP series, the musings, and just general type videos that were wacky and plain educational (with the cardboard, sharpies and everything; haha). Like when you explained factory functions vs classes or composition vs inheritance. Some of the examples you used have stuck with me till date.
      You're one of the youtubers i got the most value out of subscribing to and i understand that you're trying to grow and won't be the same forever.
      Thanks for being consistent and helpful, you're doing great and you're an amazing person. And oh yeah, we're kinda missing you on twitter.

  • @CharlesFormanWonderUnit
    @CharlesFormanWonderUnit 5 років тому

    third

    • @funfunfunction
      @funfunfunction  5 років тому +1

      I love you for posting this when there is no "second". There is no way for OCD to win.

    • @CharlesFormanWonderUnit
      @CharlesFormanWonderUnit 5 років тому

      @@funfunfunction gotta go fast!

  • @EmilNicolaiePerhinschi
    @EmilNicolaiePerhinschi 5 років тому

    yes, everybody collects data, but they don't know how to use it unless they already are targeting you

  • @Dr3amDisturb3r
    @Dr3amDisturb3r 5 років тому

    So, I learned the concept of closures before learning OOP in C#. Is this why I love JS and hate classes in general?

    • @FlexGC
      @FlexGC 5 років тому

      Ventsislav Georgiev
      there are plenty of languages that use closures.
      If that's what you like JS isnt the only language u should like.

    • @Dr3amDisturb3r
      @Dr3amDisturb3r 5 років тому

      @@FlexGC You are right, I am pretty noob at the moment, but I realized what you mention at some point. Thanks for pointing it out though - feedback is important ;)

  • @victoryosikwemhe3092
    @victoryosikwemhe3092 5 років тому

    Something I can connect to

  • @johanesterhuizen7507
    @johanesterhuizen7507 5 років тому

    First