Closures in JavaScript are like secret passageways for a function to remember certain variables, even after it's done running. In this article, I'l...
For further actions, you may consider blocking this person and/or reporting abuse
At first I though this article is gonna be a disaster (plainly based on my experience with such articles). But I've been delightfully proven wrong. It's a very nice introduction for beginners.
Good job!
I'm happy I didn't disappoint you.
Thanks!
I'm glad you find it helpful.
Not really quite correct. A closure is the combination of a function and the scope in which it was defined. I think that's probably about the simplest way to put it.
Not sure which part is not correct.
Also, I didn't provide any definition against this (function and its lexical environment), indeed I didn't even talk about the definition.
I just wanted to show the concept with two of the most common use cases by example. Sometimes I find the definition more confusing than just seeing the concept in action.
The function on its own is not a closure.
Objects are definitely not closures, and methods are functions; which are only part of a closure.
Not right. Take a look at MDN and this section in particular:
"...add5 and add10 are both closures."
This is idiomatic enough for me and I'm fine with it and I guess MDN is too.
Very first sentence on MDN page:
They seem to get a little loose with the wording further on. Semantics really, but I think it's an important thing to help avoid confusion when talking about closures and functions. Regardless, saying an object is a closure is definitely not correct.
Overall, probably better to say that a function 'forms' a closure rather than 'is' a closure - keeps the distinction.
Looking more at the MDN page, they mostly say 'form' instead of 'is' - I've made a PR via GitHub with a few tweaks to the page. MDN is a superb resource - mostly because it's community maintained like Wikipedia.
I see your point, but I think all of this depends on the context and audience.
I think for a beginner audience it's especially important to get the terminology and concepts correct early on - to avoid confusion later.
MDN page now updated to remove the confusing wording 👍
With this definition, any function defined in the global scope is a closure, no ?
Yes, but as I said, the function itself is not the closure. The closure is both things together
Finally, after more than a year. I understood properly what the heck closure. Thanks a lot.
I'm glad you find this helpful.
very simple and to the point thank you
Thanks for your feedback.