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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello YouTube hope you're having a fantastic Friday this Monday on the twitch livestream I felt like doing a little bit of our technical geeky dive into closures this stream was a little bit of an experiment because like well the new format is appreciated by a lot of people a recurrent quick critique has been that that his ad that is has been a little bit superficial it's like oh we tried this new tack oh we try this new tack and we don't really go deep into anything so I wanted to like pick one tricky aspect of JavaScript just a few lines of code and like geek out into it closures was something that came to mind for that because closures is this really tricky subject that is a general language feature of many programming languages but javascript was at least for me the first language where I encountered them and it actually took me several several years into JavaScript before I understand and I really understood truly what was going on with them closures are also fun because they have so many interesting aspects and consequences to them that you that you can explore and I think that was probably like the mistake with picking this subject because it turns out that even though closures are like yes one subject and it's like a closure example is basically five lines of code it turns out that it is a bad subject and it's very easy to get distracted by by just a single question in this topic so the live stream started out nicely with me talking about how like what closures are and and then somebody asks what our functions hoisted to the top of a closure scope and we just well like went on a little bit about interesting wild goose chase doing that and I and we learned that well you'll see we talked a little bit about how values in closures are referenced not copied which is something that is a little bit intuitive and looked at a little bit of examples of that then in order to give the example some some context I reimplemented like object orientation inside of closures which of course led to somebody asking why should I use this instead of classes and I was like no that's not the point but I still couldn't avoid going on a tirade about how this could replace classes and how there are several ways in which closures are superior to classes and a lot simple and should not be completely discounted as a as an alternative so we go a little bit on that but finally we actually end up in an example where somebody asks like weird where do we actually use some for reals and we dive a little bit into like how you can use it to inject dependencies into services that need them such as our query query functions that needs a database connection object this show was really interesting to do I can't wait to hear what you think of it write a comment down below while you're watching before we cut to the recording of the live stream I would like to thank today's sponsor Nord VPN or no the VPN nerd via peein as it would be pronounced in Swedish not everyone knows this but I'm Swedish and I record this in Sweden and therefore I know how to properly pronounce mood so what's the developer you are probably using a VPN or you sure we are in a world where like your data is very precious and therefore people are trying to get it if you're in a public public Wi-Fi hope any sort if you don't know it your data is basically up for grabs anybody can listen to it unless you are somehow protecting it and the VPN is a very good way of doing that also even if you're not out travelling on public Wi-Fi so as much as I am your data is still constant of being snooped by a lot of governments the EU and the US are gathering a lot of data and I think that saying that Russia is gathering a lot of data is not giving their intelligence service enough credit it's a norm norm data machine and I don't yet use a VPN so that they don't get all of it at least at least that's the way I'm thinking about it the VPN is also very handy if you need to check like your country filters and see what happens to you website when you come from a certain country nor VPN has allows you to you that's service in 62 countries I also like to note VPN is Open VPN base you can use it on anything that supports that your router and everything you don't need to use a special app there apps are really good but and minimalist like me I really enjoy being able to use it client less don't get me wrong they have great clients but I've had bad experiences with VPNs where they kind of just like force me into using their custom client and I'm kind of like dude let us date a little bit first so if you do not have a VPN mm-hmm go to Nord BPM org slash fun fun function and use the coupon code fun fun function if you sign up for that three-year subscription which makes the monthly fee insanely low then you get 75% off plus you get an extra than that as well Derr Derr jerkle asks what our closures so let me let me declare a variable here that is called X which is a dreadful name dreadful name for a room and I'm going to call that waffle and then I'm going to return another function that we call a call in a function these are really like can function in a function and I'm going to to return I like office now yeah X and you know what I'm gonna rename this food food and I will then yes go generic function call this what does that give us I'll start Kaka oh yeah this gives us an inner function and then I and then I then I call that and I get I like what let me fix that there we go okay so but this yes a little bit mind-boggling so if you're not used to if you're not used to closures this might make you feel weird because if you're coming from another language variables they don't really exist and in the world of in the world of like this would stop existing once the function has returned but in the world of a language that has closures this variable keeps existing it keeps like the inner function has access to its - to this space here as well see so let me we could perhaps like I'm gonna do a lot of like fiddle around with this in in a lot different ways until you kind of get it ronan asks ran the questions that i don't know that i've ever thought through or inner functions hoisted it to the upper scope this is a bit of a like more advanced question but yes they are I think that I'm pretty sure they are that funny I think that every function is always hoisted to to the upper scope we can actually check this let me call in a fraction here what happens did I do that no you can't I actually expect this to work that that it would automatically in before doing the compilation I thought that it would do that but it doesn't huh you learned something new every day it's not wasted or perhaps it was you smiling true now I wait was it just one entry no no it's an error in wait yes it's my limiter hang on hang on this was just lynn turner yeah because this is horrible practice to write this way but let me for a while no I don't have the link to added to this yet how do i you write can can somebody look up how to write es linked they ignore is it like this ignore look at this no under that it Valdez 89 what is the plugin that you use that shows the errors in line its Quokka there we go fifth in our clip and gave us the solution give it to me like this now it's still it still refuses on above on the line above okay there you go yes no I'm sorry [Music] alright so Cheney nuclear there we go alright it's so fast though still fails interesting oh prototypal says unlike 99% shore only function statements get hoisted and all right let's do that function inner function which an inner function oh oh that's so interesting so it like that is different so you see here now as you see like I can call inner function before it is defined and that that is because in JavaScript there's a thing called hoisting which means that it actually like will before compiling it it will just send all things to the top and I like some things to the top and functions is one of those it sends them to the top of its inner image like it's the function it's being containing so this is actually what is being compiled so to answer your questions functions are hosted all right so let's let's let's call this let's go for the dragon examples gonna go a dragon and we are going to call have Const breath because you can use like closures as a very good like you can use them to implement object orientation in JavaScript and this is not necessarily something that like we should be doing with closures because we sort of have classes for that and you can I'm a proponent because I hate classes but since this classes has yeah yeah yeah yeah you can just let's just leave it that oh and it's College fire and we going to say preference and then we're gonna return function attack and return I attack you Wade right for 10 damage oops did and then we return reference and then we can go Const drive home now we go Fluffy's and we call it dragon and now as you see here this is an object that has preference and attack and we can call professions dot preference and that gives us I like waffle and we can call attack and that yes I attack you with fire for 10 damage and I would like to stress here that these are like this is a living thing this closure so you see like and so that the function is not really closure it closure is like the functionality of preference having accesses stuff in there they're outside scope over there that the function that they are being contained in a more 94 maybe I'm an idiot but why would I use this instead of classes we're gonna like I'm just using this example here to show it to you in a context that you understand that this is not a replica closures are not really a replacement for for classes that can be used as that but they are way more useful right now I'm just using it to like make you get what they are we are getting to the why in a bit but we're focusing on what first so I'm gonna do something like if it was Kim see here like I'm gonna do let damage and it's gonna like 10 and then we're gonna have like function level up and that will increase the damage how do you do this this 10 zoom out a little bit and well let's exposed to the vlog so now you get here like attack with ten damage and then I go love begins dot level up that gives nothing and then we get like Oh what didn't that work yeah it won't see much I actually expect that the second one here to give damage oh it's because I've hard coded damage so as you see here Ronan's it's hard coded yeah so as you see here like this this is this is actually not copied the the values of these are not copied they are actually attack is actually accessing what the variable is right now and this is a little bit that this I tripped over this a lot of times before when I learnt closures that I always thought that it kind of like froze in time when I was when the when they think what like but it isn't like this is actually references template literals I'm dying here oh sorry babe I'm gonna it like everything beautiful fitness a longtime member of of the community see here let's see here I barely remember how to do this there we go or templates numbers then weekly or else are pretty dope like though since I'm 35 I'm allowed to say dope really said okay where's that like some kind of dad thing let me retract do this as well getting distracted here there we go there we go and there we go okay that so let's get back a little bit to why I explained here like this in the context of object orientation a little bit because I want it to be being in a context that you you understand but this is not really demonstrating like why closures closures exist there there is like cases for building functions like this because this is a very very clean and simple way to do private things private variables so for instance like if I if I wrote like fluffykins dot food here I can't access that oh sorry I need to do that after there like it doesn't exist however if I had like if this was a class class buff Akins sure this no last dragon dragon Oh God thanks Visual Studio for nothing tell us is the most overrated thing flame be and we have something like that is the food and how do you even do this how do you declare like forgotten this in classes because this oh yeah I'm a constructor and intellisense intellisense rock tour stop what is this wrong here something breaks always and type checkers and I'm gonna do this dot food equals bomb and waffle plus there shouldn't have been separate tanks and we're gonna copy this preference here help and food is not defined I'm gonna go disco food so I'm gonna do a new dragon and call it love off a king's from plus and then we're gonna see here that I can access food here so it doesn't matter if I do things like this I can keep naming it like whatever I want like man like the class people do but it's still gonna be accessible like you can't hide it can't hide the implementation there are extraordinary convoluted ways to do this in classes and it's classes are getting proper private members in some new EX Mode the script version but I sometimes just feel like classes is such you can do exactly the same thing in closures already and classes to me or like it seems like it's Java developers that really want Java scripts to be just like Java and they are doing so much work to make it be Java instead of just using using closures another benefit of using closures is that you out of the box let's say that I do this fluffykins know from class and then I do preference and then I do coast yeah like and I call that then things break and the this is like this is a little bit convoluted examples because this refer this happens when you assign this to an event handler and react or something like that and but like I can do that like if I go here and do like the same thing with a with a closure object see ya go like in stock preference let me zoom out a little bit oh god I've written a lot of code here come on it's too much a little bit more so much we're getting way too much here by the way well we're we're we're at it I'm gonna share my collab session in a little bit make read-only there we go now wait I can't do this while using quokka shut because it gives you access to stuff I'm not sure of the complication that's what we're not gonna do that sorry yeah a quota is the name of the extension that were using here right very nice yeah so look I'll call this F and to like I'm gonna call that and then fight with pushes studio come on the card I now please don't die oh yeah hang on I need to disable that CC here like even though we do this reassignment here this still works because because of closures so here like the class is not making use of closures and preference does so there are that there are things that you can use arrow functions in in classes to get rid of this so I think that you do something like like this and that makes it work I don't know how some way this way it may be there now it will work wait no no wait why doesn't this work I expected this sort of work this is even componentry now this is probably crushing some bubble or something because this is a requires cross-compilation or stuff oh hang on yeah it should be just up food Thank You prototype oh thank you so much so have a look at this end of what yeah and T equals Allah so now I think it should work now just yeah yeah yeah this is I think this theoretically should work but like it requires like quite a bit of bobble magic and also under the hood this recompiles into some rebinding garble that will completely destroy the like the memory benefits of classes like the Reis the main recent use class is over this because this is very elegant and nice it's just it's very clear what what it does once you understand closures but the dragon here you like there's a lot of weird things going on with dragon so the main reasons to use classes yes that is for the memory reasons that we don't recreate these functions every single time we create a dragon but when you do this that means that the function is under the hood recreate it every time so you basically just using classes for no good reason in my opinion like if you use these plus that you also like have to write some class some functions as we might need to do some classes as as arrow functions so because like this wastes memory like it's just like this why I can't like to create objects like this because there's so little magic involved and this is not even taken into that account like all the weird stuff that is on on an object like like this if you just have a look at it can you see that here Oh God yes lint it's a look can I just inspect it I like extra prototype and this what it's like that is so annoying that type chicken really annoying Oh makes it's so hard to work see here yeah either way no it's like proto I think it's proto something like this oh I'm dying from this year's Lynch it hang on how do you disable he isn't there was somebody that wrote he is link disabled there we go he is link go die [Music] now still doesn't allow me but nothing like that yeah I assure you that this thing is here but quokka won't let me show it maybe coca is breaking test won't fail our closure there's an invalid syntax somewhere syntax are unexpected - all yeah because it's yak waka is not parsing this it doesn't have a ball ball that it's late enough to handle this I suppose or something let's do that there there we go so here we see that it has like these proto objects and I maybe this dust you maybe this is a bad example see does this have a proton no it doesn't like oh it just has an empty object like everything and yeah I like flapping in school class also has this thing Pro this is like pro to top Oh No yeah this doesn't have that it's it's this that has it yeah but I don't if I call fluffykins yeah like Simon Says that prototype is of the actual yeah function right traffic ins dot destination Airport type [Music] no it does not and also the dragon here is not our prototype and like you have like prototype more is the prototype like if you're gonna like use classes now you go have to go learn about prototypes because classes in JavaScript you just like this thin abstraction on top of on top of the prototype and that's that's just it makes it so hard to deal with classes in JavaScript arguably this is because how clauses are implemented in JavaScript but yeah like all this weird prototype stuff and binding stuff I there is a like there is definitely a case for working with objects in this way even if like the memory usage is slightly higher origin says where do you use closures so I talked a little bit how you can use them to to implement object orientation but that is not so much whether the most practical case is I would say that we can't throw this way and we can have a look I'd say let's say somebody had an another excellent question yeah upgrading Dave said if you're designing an API say for example something that needs a database connection do you write a bunch of functions as closures around the connection or do you prefer to pass a database connection as an argument in each of your methods in the API I like this because this is a case where I use use functions use closures a lot so let's have a look at let's say DB connection all right in the database and let's say that this gets a connection and then we have a function called query something like this yeah let's do this create something like that maybe and we're gonna call it quick trip this is a little bit convoluted names but we are the for pedagogy we're gonna do this and then we are going to let's say that there is a method on the connection objects that is like query and this seems a little bit unnecessary but like let's imagine that you're doing a wrapper around this and there's stuff happening requires you do this and there's like some sequel here and this will return the object and put a bit of pop pop pop pop and we do and let's say that we have an Oreo class like in order class let's say an order function function and pom pom pom pom create order and this is dependent on a connection I know maybe and this returns now we're gonna we're gonna call this right order function and we do something like God [Music] and this does connection dot query and then insert order la blah blah blah blah blah and in when we instantiate the app we want to the problem here is that we want to be able to share our connection across that we want to inject this in the finished connection into every every object but we don't want like pass around the signatures everywhere we want to like make the order function not aware of no hang on I'm gonna do this this is what more sensible like this we want to have like the order function unaware of the concept of it shouldn't be aware of more than it needs to be so when we're doing a dependency injection we might do function don't go change engine to do let's do like this order and you do a great order function and this requires a connection now this requires query and then we do need to also create that create a function almost where and this requires a connection which then might be like new MongoDB and then like config nekron and here's some like username 1 2 3 and now quokka is not helping us because we're not working on real code but what got stopped Connect connection there so this is a little nice because now we have this disorder function so like the same that we have in an interface function I don't know like say we are in on the top level and creating like a react app and we need to pass down order stuff this would be passed down in other ways in react but you might get the idea so now we can pass just order in and order wraps another thing that contains another thing it contains it contains another thing and you can you can do this with classes but and that's like done with this kind of like configuration object from the configuration objects but doing this with classes is so heavy like it's it's it's a lot of construct to do something and add that it that it really doesn't because these these these things that contain state they are just like they're just carrying around like a reference to another another object or perhaps a configuration so like using functions where this is it's very sleek and now I'm doing it in absolutely most verbose way I could also do something like did you do Const say like query factory and then I'll call this beep beep boom boom like this and I can also do this and do the same thing for this where I asks like use of arrow functions oh my god it's so much stuff I can remove from this there we go now we actually have to go forward in sequel yes see there we go there we go there there sorry about that sequel something like that I guess we need to forward the connection as well no sorry we need to for the query gets a little mind-bending with dependencies there we go oh those are not necessary so something like that and we have like a billion more questions or enclosures but four out of time and I don't want to run this too long we will probably do a follow-up to this because closures is like this infinite infinite subject and and yeah we're gonna do one more definitely I hope that this confused you more in a way that perk your brains thank you so much for watching don't forget to check out our sponsor Nord VPN Nord VPN dot org slash fun fun function if you're thinking about getting their three year plan which makes the monthly fee insanely low use the coupon code fun fun function because that makes your gives you 25% off and it gives you one month extra free if you like the show it might interest you to know that we record them live on Monday mornings check out what that is in your time zone at twitch.tv slash fun fun function if you want to see more about what fun fun function is about you can check out this playlist or if you really really like that you can just go ahead and click Subscribe right now by clicking here I am mpj until next Monday morning stay curious
Info
Channel: Fun Fun Function
Views: 21,340
Rating: 4.8104577 out of 5
Keywords: programming, coding, javascript, computer science, software engineering, software, functional programming
Id: F3EsDDp4VXg
Channel Id: undefined
Length: 45min 53sec (2753 seconds)
Published: Fri May 17 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.