I think the first example what you have shown is wrong. In order to call a function a closure, the called variable should be present in an outer function rather than just a global scope variable. There needs to be an outer and a inner function to call it a closures.
It is not clear to a person who may come from some other programming background. It looks like, "yeah, isn't such a variable access obvious. Why does this need another jargon" The essence of closure is only highlighted when a function is wrapped inside another. I had the aha moment, when I read this on the mozilla documentation. Hope that makes sense.
Agree. I think MPJ should've made that clear and give examples with inner functions to show the utility of closures. But my point was that I don't think the example he have was "wrong". As I see it the closure is the capacity of the function of "remembering" the context in which it was declared and having a reference to the variables that it uses from that context. It is also important to highlight that this is regardless of the lifetime of that context. I can be wrong though and finding if that's the case was the main purpose of starting the discussion :)
Hi, thanks for doing this! I have a small comment: you should have picked a better first example. The reason is that even in languages without lexical closures (at least some of them), the example would give the same result. The difference is that, while with a lexical closure, the free variable are resolved from the lexical environment (the source code structure), in a dynamically scoped language it is resolved at runtime. A better example that I think is easy to understand is the classic "makeAdder" example, where an inner function (returned by the makeAdder function) captures the parameter sent in to the call to makeAdder. Keep up the good work!
I was very impressed by the first 4 videos, and I learned something from this one too, since I hadn't thought about closures before -- yet somehow this episode didn't give the same tingle. "Here's an example, there's many reasons to use it... now go look it up." - I did and only got half way through the documentation (I'm a bit tired, and only one month into JavaScript (learning it as my first programming language), so maybe I'm not the target audience, but the other videos made thinking about difficult stuff so easy! "Functions are not just functions, they're also closures. What that means is that the function body has access to variables that are defined outside of the function body." doesn't have the same explainatory ring to it as the ones in other videos like "Recursion is just a function that repetatedly calls itself until it doesn't." -- I can't tell for sure what would have worked better, but I came back to this video after stumbling over closures here ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-_EF-FO63MXs.htmlm24s -- the diagram showing that the set of variables that the inner function can see encloses the set that the outer function can see somehow helped... but I still feel like I'm missing something. Maybe it's just because this topic is somewhat easier to understand than the others, so I'm not getting that "click" experience, and that's why I feel it's incomplete... Anyways, your other videos are 11/10 to me, and this one's just a perfect 5/7 --- :-P Thanks so much for your work and good humor!
As per video 9 - warning that the above comment may not have been raised for its merit (i.e. I don't see how an old video would change) - I just wanted to share my opinion...
i've found understanding closures to be a long, continual process. they may seem simple at first, but there's a lot happening behind the scenes. in all fairness to +funfunfunction's wonderful vids -- including this one -- a short tutorial can reveal some basic behaviors of closures, but it's just the tip of the iceberg. closures touch on core aspects of javascript's design as programming language -- object hierarchy, functions as first-class-citizens, function scope, prototypes, etc. -- and enable much of its powerful functional and object-oriented features. here are some resources that are providing me with 'explanatory rings'. maybe they will for you too. GL ;) jibbering.com/faq/notes/closures/ github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures
o_O buddy, at the time you made the video you really had ABSOLUTELY NO IDEA of what closure really are have been watching the playlist 'Functional programming in JavaScript', parts 1 to 4 are made SOOOOOOOO GOOD. i think i'm gonna keep on watching the playlist but i do hope, that this was an exception.
The way I internalised closure was during a job interview where i had to type in a searchField to sendRequest to an api but with each additional letter my initial request needed to be cancelled and a new sendRequest made with the added letter in the searchField. Before that I did not understand the concept no matter what I read on it. Coding out real world examples can help to illustrate a point more clearly. Once again, nicely done.
I would really like an episode about promises, maybe more then 1 episode, like how to promisify, how to enrich already existing code with promises, how the different higher-order functions work with promises.And after that, higher-order functions with json streams?
Hi Nice video. But correct me if I am wrong, you just explained lexical scoping, not closure. In essence closure remembers the lexical scope even after the function has executed right?
Thank you very much for your videos. I especially enjoy when you take us on one of your walks and get philosophical. Those are a special treat. On the topic of closures: I am wondering how much memory they use, since each closure has to keep track of its context, and I assume its parent's context, all the way up to the global object? Could you make a video about this, and why it is or is not a problem when using lots of closures.
I just want to say that I really enjoy your videos. You do a fantastic job of explaining the concepts and code in a very entertaining way. I'd love to see some more videos on the techniques you use for functional programming - how to "foresee" the end result, or 'composition'. I'd also be very interested in your explanation of Promises, and the best ways to take advantage of them.
Noah Namey Thank you for your kind words. Can you elaborate a bit on what you mean by "foresee" the end result, I'm not sure what you are referring to?
Umm... I guess I mean how to approach a problem from a functional programming standpoint. Is it just a matter of breaking things up into the smallest self-contained steps as possible?
I'd like your version of this talk - with more 'enterprise level' code. And BTW, I'm also really thankful you're willing to share your time. You're helping a lot of folks.
I have been really enjoying these videos. Thanks for making functional programming videos not boring. I have been using jquery for years, and never really understood why it works the way it does.
Thanks for all of your videos MPJ! Starting a coding bootcamp here in the Uk next week and these are helping massively for the pre-course work :) Keep them coming!
I love your videos. It's true that you said there are a ton of other use cases for closures. But I guess the most important is encapsulation. I'm just throwing out an example here for the folks watching. In the example below you can increment counter only by calling add(), and there is no other way to do it. var increment = (function() { var counter = 0; return function() {return counter +=1; } })(); increment(); increment(); increment(); console.log(increment()); // returns 4;
Hi, I've been following you on Quora and recently came to know about your videos. These are some great lessons indeed. It'd be great to have a video on callback functions and the synchronous/asynchronous thing with JavaScript, there are quite a lot of people who get confused with these at the beginning and a video from you would be really helpful.
the main problem with this video is that not every function scope represents a closure scope. a closure is a function execution scope that can have and use variables from a parent function execution (function in function), althought that parent function was already called and implicitly its execution scope was deleted from execution stack. for this topic one needs to understand: execution scope, call stack/ execution stack
Love your vidz MPJ. However, I can't agree on the first example of closure on these video. *me* is a _global_ variable. _Globals_ live as long as apps lives, in contrast _local_ variables live as long as function (which they are scoped to) runs and garbage collected when it is finished. As it is stated in "You don't know JS" series: _Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope._ Thus, in the first example, function is invoked in the same scope. It's not closure. If I'm wrong, correct me :)
No, you were right on the first place. Easy way to prove it is to type one more line: console.dir(greetMe); please have a look at jsFiddle jsfiddle.net/Eugene82/k444t8vk/106/ in the console you will see function with 2 scopes: Global and Closure. See for yourself where "me" variable sits. PS I'm using Chrome.
Also think he was right on the video. It's the same concept. A closure is a function along the lexical environment within which that function was declared. If he were to call the 'greetMe' function inside another function that defined a local 'me' variable, the global 'me' variable would still be used because the 'greetMe' function remembers which context to get the variable from. Illustration: jsfiddle.net/qr64w847/1/ And the reason why it remembers is the closure. The interesting thing in the case of wrapped functions is that the local variables aren't destroyed at the end of the function execution, as one might expect, if it is being referenced in the closure. Thanks for the video, Mattias.
Closures.... One of the most underappreciated and under-utilized features of functional programming. You can build-up and tear-down(execute) complex sequences of steps with closures.
Hey Mattias, another great video! I do have nightmares about memory leaks every time I heard in closures!! Please help me to sleep well and MAKE AN EPISODE ABOUT MEMORY LEAKS!!
I second @Vishal, the video is a great introduction to the concept, but a pretty critical part to understanding closures is understanding that in JS a closure is the COMBINATION of a function and the lexical environment within which that function was declared. The really wonderful / magical part of closures is code like: ``` function makeFunc() { var name = 'Matt' function displayName() { alert (name)} return displayName; } var myFunc = makeFunc(); myFunc(); ```
MPJ, another great video with a lot of energy! Just wanted to re-emphasize Vishal's point on creating another video with a function inside a function example, to make closures more clear.
When I first found out about lambdas in C++ I thought they were the coolest thing ever, and wondered if there was something wrong with me. Now finding out about this whole functional programming world feels just... magical.
that's not ironic. it would be ironic if, for example, he saw himself as a very up-to-date kind of guy, and at the same time somehow missed that functional programming existed. it's not ironic to not be aware that something exists, even if it's old. it could be ironic that you don't know the meaning of the word ironic, if you were reeaaaaally old, because it's implied you should know the meaning of the god damn word by now
Your first example wasn't really a closure. It was just normal JavaScript scoping. Closures, on the other hand, are inner function that have access to variables of their outer functions even when those outer functions have been unwound from the stack. That is why functions that return functions are so powerful.
I'm at 5:07.requestID is already in the sendRequest() and so is the S.ajax function-why is it amusing?When both are under the same function-for one to be able to access the other isn't no big deal right?
This video doesn't really get at the significance and use of closures but the link to the Mozilla JavaScript documentation on Closures does. Recommended, or seek other tutes on closures elsewhere. Great series of videos though, makes these concepts all seem very straightforward, easy peasy and fun
Love these videos, thanks for posting. Just subscribed! One idea for a future video (outside of promises which has been mentioned a lot) would be recursion!
This is the second time I am going through your playlist of Functional Programming - just because I really love your way of explaining thing - now I have an open ended question to you. Great Work - Kudos. There are lots of resources around the web for JavaScript, Mozilla's documentation being one of the best (at-least I like it). I need to ask you regarding other resources - which concentrate on FUNCTIONAL programming in more detailed and a bit advanced level. Few books I came across were : 1. JavaScript - the good parts - Douglas Crockford 2. Secrets of the Javascript Ninja Can you suggest few books like this which I can refer for Functional Programming as well as ECMAScript 6. Your inputs will be highly appreciated. Again thank you and keep posting amazing videos like this. Keep up the good work.
+Yajurvendrasinh Gohil im sorry, I have nothing for you. I read very few books nowadays. @getify is doing a crowdfunding campaign for a book on the topic, I suspect that will be awesome.
Watched all your videos in your series in one day! I like the way you explain your lessons. I've been reading different articles on callback functions as well as videos but I don't quite understand the practical application very well still and when to use it. So an idea may be to explain practical applications for callback functions.
Damn! you are the f*****n boss! So much fun - and so much knowledge! Only watched some of your videos and went back to coding - actually just trying to finish a project that I started. And baam! What I've learned from you had an immediate impact on my thought processes and the way I approached things. Thanks a lot for that and keep hacking :)
Great videos here! Really felt like there was a missing channel that described more intermediate javascript techniques. Wealth of beginner content but not a lot to go on from there, you've certainly filled the gap! Thanks. :)
Glad you enjoyed your vacation. Thanks for the closure explanation. As you mentioned you need to use it in your code often in order to fully understand it. I was wondering if we could have the next episode be about OOP and how to implement it in a real world example mini app. Thanks for the videos, I believe they are reallt useful..
function createBase(baseNumber) { return function(N) { // we are referencing baseNumber here even though it was declared // outside of this function. Closures allow us to do this in JavaScript return baseNumber + N; } } var addSix = createBase(6); addSix(10); addSix(21); How this is working?
Is it okay to assume that since closures are 'side causes'(variables that the function depend on, but not specified in the argument), it should be pushed as far out as possible in code base if you want to use more pure functions? really enjoying the whole series by the way. thanks a lot!
I meant avoided as much as possible, but it turns out closures can be a part of pure functions. This Stack Overflow post clears it up. programmers.stackexchange.com/questions/235175/are-closures-considered-impure-functional-style
I also disagree with the first example. It's just a global variable, it can be accessed by any functions. It is NOT a closure. A closure is related to the execution context... not global variables.
Absolutely true, the first part of the video is 100% dead wrong. Every time I watch something from MPJ I lose respect for the guy, more I watch him, more I think he doesn't have a clue what he's doing. Just watch his a video about composition vs inheritance.
I wanted to know about the IDE setup required for MEAN architecture... Which JS libraries should be must to learn for an entry level Java script Programmer
+lalit borse 1. A text editor. Very few of the professional JS developers that I know use IDEs. 2. Frameworks change pretty rapidly, so it is more important that you have a firm grasp of the language. Angular is a super-overrated framework that is used by a lot of companies, so if you're looking for something to learn that will land you an entry-level position, that is a good bet. React is growing as well. That said, frameworks come and go, the language stays stable, so for long term job security you should really concern yourself with a good grasp of the language itself.
Hi, this is a great video and I really enjoy your channel. However, I am just kind of confused on how this is functional programming. Could you make a video simply explaining what functional programming really is, like in theory? That would be awesome MPJ, ur the best
I'm a complete newb so I'm a bit confused X_X I only have some basic student level experience with Java and this just seemed like standard scoping to me? Is the "scoping" in java also "closures" (the way access trickles down) and I just haven't been exposed to the terminology? Someone help X_X
So, I really love your style, delivery and content....but wishing there was more....any chance you have full length courses that I just cant seem to find?
Wow! BTW, as part of my master's degree i'm conducting a research about motivation to contribute to open-source projects. I will be honored if mpjme himself will fill out this short questionnaire. goo.gl/forms/hXwTjtr1kL
hello, I checked Mozilla JavaScript documentation on Closures , in the second example, "return displayName" will return the syntax of that function witch is "alert(name)" not its value.. thanks for ur great videos..
Thanks for the link to the Mozilla/JavaScript discussion of closures. I found it understandable until the part where they discussed problems with closures and loops. I'll get local help. :)
Hey Mattias! Great courses, thank you for posting every Monday. What do you think about functional programming with RxJs, and more particularly with DOM events ? Cheers,
I really, really like Bacon and Rx etc. I think event streams as a general concept is bizarrely useful and way overlooked. I really recommend thia article if you want your mind blown out of your ears: www.confluent.io/blog/turning-the-database-inside-out-with-apache-samza/
I am so happy to have found your channel! Thank you for your unpretentious explanation of these concepts. You make me feel as though it is simple and that I van easily learn this terms that have, more or less, eluded me in the abstract.
Hey, first of all, I'm really enjoying your Videos. They're a great help for someone like me who's just earnestly started trying to learn JS. Secondly, I just wanted to ask a stylistic question. I noticed you didn't use semi-colons and just wondered if this is generally acceptable. I get pinged by jshint all the time for forgetting semi-colons so I've started to get ocd about them now. Is it acceptable style-wise to leave them off when you can?
+mpjme awesome! Thanks. It's good to know there is more than one school of thought on it. I'll give it a try, and if nothing else, it'll teach where a semi-colon would really be necessary.
So this just means that JS functions can access and modify global variables without having to pass them by reference via pointers/references as you would in C/C++?
+Phillip Vance no, not quite. I should have used another example. It can access variables that exist in scope when the function was defined, which is not the same as a global variable.
Fun Fun Function ok I think I see...so it's the same scope the function is created in, which in the case of your example just happened to be a global scope?
No, it was not a global scope on the first place. Easy way to prove it is to type one more line: console.dir(greetMe); please have a look at jsFiddle jsfiddle.net/Eugene82/k444t8vk/106/ in the console you will see function with 2 scopes: Global and Closure. See for yourself where "me" variable sits. PS I'm using Chrome.
The most common example is callbacks. They are not possible without closures. I.e. lets say that you fetch some data asynchronously and you want to update some label text based on that data and some other data in the function, when the data arrives. In a language like Java which lacks closures, you have to create a pretty convoluted structure with classes and state.
function addWhat(num1) { return function(num2) { return num1 + num2 } } var add3 = addWhat(3) console.log(add3(2)) // 5 In this example, the function add3 'remembers' num1, which was passed in as an argument to addWhat. This is a powerful example of using closure in JavaScript. Let me know if you have more questions!
+Julian Klumpers not quite, that's a different concept. I should probably make an episode on that subject because it's a bit hard to wrap your head around.
Awesome MPJ. You explain things very well. BTW when you said "this is a series where we learn functional programming in javaScript" - my "be careful" sections of brain got activated to be clear about what "this" is referring to lol. the this keyword creates brain damage you see.
JavaScript is so rife with closures it's almost hard to program in JavaScript without ending up creating them. The problem with them is that it's not always super easy to avoid leaking boogles of memory. I've written several programs that use setTimeout to facilitate looping for a long time without making the browser unresponsive. After a while, if you look at the heap, you've got these enormous context chains. If there's any touching of the DOM in any of that, you're really in trouble. Even if there isn't, it's just a bit of an ugly mess. I would like to see how you can create long running processes in JavaScript that need to loop over and over using setInterval or setTimeout and in the process of each iteration need to access what amount to class instance members and so on without winding up generating big long context chains. How can you pass "this" (or "self" or whatever) into a setTimeout, over and over, without either using a singleton or accessing globals, and without creating an enclosure and thereby ending up generating a big long context chain? What I've ended up doing is essentially something that amounts to using singletons and/or globals, which is fine in JavaScript because it's actually single threaded anyway. But it's sure not exactly what I would call an elegant solution. Anyway, if anyone listens to this and JavaScript enclosures are new to them, they should make sure they understand the ways that using enclosures can end up leaking memory.
MPJ I wonder that you were so good at VI as u mentioned in episode and u spent time to learn and customize that editor for u then why u left VIM and start doing work in Atom. I m not saying one editor is better than other but once u have done all this in VI then why using other editors and start forgetting what u learn?? does that make sense
Great videos. Thank you. I subscribed and followed you on twitter.
8 лет назад
Hello, Mpj! I don't pretend you solving me programming problems, but I can see you love to teach, so I dare showing you a piece of code I have problems with and that has todo with Closures: function coso() { var a = 1024; coso.prototype = { get a() {return a}, set a(valor) {a = valor} } this.muestraA = function() {if(a === this.a) {alert("¡Yupi!")} else alert("A vale: " + a +", pero a vale: " + this.a)} } I am not able to link or to make the equivalence between tha var "a" and the property "a" (Trying to do so, I entered the prototype defiition into the function Body). Can you explain me why is this so?
+Rafa Gómez i don't understand what you are asking. A general advice: Clean up the code, isolate the problem, and translate to English before asking others for help and you will have better results. Make an effort for the people that you want to help you and they are more likely to help you backs
8 лет назад
Sorry! I will try to make me "understanable": I wanted to make a property of my object of type "coso" that sets and gets the variable "a". But I don't know why, the functions seter and geter doesn't see the variable "a" that is defined inside "coso". I have tried various approaches but I haven't been able to achieve this simple request and asume it's got to be something related to the scope of the variable. I tried to clean up the code most I could because I had put a LOT of alerts and tricks to try to seek where the problem lies, but evidently it didn't work, so I think I'll rephrase my question: Can you tell me how to make a property of an JS object that sets and gets a value that I am gonna have in a variable? I am not used to OOP, perhaps my way of seeing things is obsolete. Thanks for the patience.
Hi sir, Thanks for your tutorials, Simply super................ I have a question....Can we take data outside the "Ajax Success method" and use in out script ? Like this var finaldata; $.ajax({ url:"myUrl", success:function(response){ finaldata = response; } }); console.log(finaldata);
Thanks man..you are right... var dfordata = ''; $.ajax({ url : 'cool.json', dataType : 'json', // if you omit this line the default dataType is text success : function( data ) { dfordata = data; alert(dfordata); } }); $(document).ajaxComplete(function(){ alert(dfordata); }); this worked for me...
mpjme Thanks. Might be worth mentioning that in the future though. I was scratching my head a bit because I already knew about this and I couldn't see how it tied into the rest of the series. Side note: Love it! Keep up the good work!
+Mohamed HASSAIRI it's an internal property of the function and you don't need to be concerned with it unless you are building a JavaScript engine or something. You can read a little bit about it here: speakingjs.com/es5/ch16.html