JavaScript Closure Part Something - javascript

Hello how are you? I'm Steve.
I have found and read the sentence which is quoted below.
In programming languages having first-class functions, closures (that are also called function closures or lexical closures) are a technique for implementing lexically-scoped name binding. Concerning its operation, a closure is nothing but a data structure storing a function together with an environment, which maps all associating each free variable of the function (that are used locally, but defined in an enclosing scope) with the value or storage location the name was bound to at the time the closure was created.
Does someone make sense of "... maps all associating each free variable of the function ... "? I would think the portion of the sentence should read "... maps all associating and each free variable of the function ... " I was grateful of any input.
Thank you
Steve

Related

What is the global scope in javascript? How can I create one?

When running code on Chrome Inspector's console and typing the this keyword, I can see the global scope object that is exposed with many properties already set. But, how can I create mine? Or when I call a function, the call-site is the "global scope" of that function?
I'm reading YDKJS book series and some concepts get really confusing sometimes.
First of all Kyle Simpson's series You Don't Know JavaScript is very nice. Few know that topic as well as he does.
Second, in the context of a browser, what you are calling global variables are all variables that are owned by the Window object. So, keep that in mind when naming them so you don't clobber an existing and important property.
Third, learn more JavaScript and realize you can generally avoid using these types of variables

What does a closure REALLY refer to?

I know how to use "closures"... but what does the word closure actually refer to?
On MDN the definition is that it is a function. Here is the page about closures. The first sentence is, "Closures are functions that refer to independent (free) variables." and in the first code example there is a comment highlighting the closure function. However, the second sentence seems to suggest that the closure is really the persistent scope that the inner function resides in. That's what this other stack overflow answer suggest, too (search word "persistent").
So, what is it? The function or the persistent scope?
Technically, a closure is the mechanism behind how persistent scope works in functions - in other words, it's the implementation. That's what it originally meant in terms of Lisp. And in some cases that's still what it means - just look at the explanations of what closures are in various Lisp dialects and they almost all try to explain it in terms of how the compiler/interpreter implements closures. Because that was how people used to explain scope.
The first time I came across a much simpler explanation of closures (that is, explaining the behavior instead of the mechanics) was in javascript. Now that more people are used to the idea of closures, the word itself has grown to mean:
the captured scope of an inner function allowing the function to refer to the variables of the outer function (this is the closest to the original meaning)
the inner function itself (typically in languages that call first-class functions or lambdas "closure")
the free variable captured by the closure
I personally prefer the last meaning because it captures the essence of what closures are: a form of variable sharing, kind of like globals. However, if you want to be pedantic, only the first meaning is actually the technical meaning: "closure" refers to the captured scope.
To answer your question as to whether the closure is the function or the environment, it's both - it's the combination of the function and the environment which it makes use of. It's especially important (and may really only exist) in the context of languages where functions can be defined (often anonymously) and passed around as parameters to other functions (witness, for example, the use of blocks in Smalltalk, anonymous functions in the Lisp/Scheme sphere, and etc). The issue is this: if global function A is created during the execution of function B and A references a parameter named P which was passed to B; and if A is subsequently stored in a variable V, and is then invoked through V after B has returned, A still needs to have access to P (which was a parameter to B, which has long since finished by the time A is executed) in order to do its work; thus, A must have a "closure over P" in order to do its job successfully. The "closure" is a combination of function A itself and the environment set up when A is compiled which stores a copy or reference or what-have-you of P so that A can do its job successfully.
Note that despite having used languages which make extensive use of closures (particularly Smalltalk and some Lisp variants) this is usually so well buried that it's beyond transparent - you don't even notice it. If you notice that there's a closure, IMO it's not well done.
YMMV.
Best of luck.

What does Crockford mean: "Javascript depends on global variables for linkage"?

In Javascript: The Good Parts Crockford writes that "Javascript depends on the global variable for linkage." I understand that in javascript if you declare a variable outside a function it "is in the global namespace" -- meaning you can access it anywhere in the program. I sort of understand how linkage limits where in a C++ program you can access a variable (regardless of its scope). With that said, what does Crockford mean?
I think what he means is that global variables are how you communicate with libraries. For example jquery uses the global variable $, underscore uses _, etc. You link to the libs through a global name.
Continuing
All the top-level variables of all compilation units are tossed
together in a global namespace called the global object. This is a bad
thing because global variables are evil, and in JavaScript they are
fundamental. Fortunately, as we will see, JavaScript also gives us the
tools to mitigate this problem.
What Crockford is referring to, I think, is the absence of module or namespace-like mechanisms in JS to segregate and modularize chunks of functionality at a macro level, where those chunks are explicit about what they are exposing (export), or what they are using from other chunks (import). However, as he points out, JS does provide the ability, albeit imperfectly, to do this through existing language features, and the world has not come to an end. At the same time, this problem is now being addressed on a number of fronts, notably the ES6 module mechanism.

Is it possible to iterate over all properties in a JavaScript closure?

for ( var i in this ) { console.log(i); }
With this loop, I iterate over all properties of an object. Is it possible to find what local/closure variables exist?
No, there's no way to examine the contents of a scope, because there's no way to get a handle to it. (The global scope is excepted, because there are ways of getting a handle to it.)
What I mean by that is that there's no way to get the runtime to give you a reference to the scope as if it were a JavaScript object. Thus, there's no way to explore the properties; there's nothing for the right-hand side of a "for ... in" loop, in other words.
edit — if one could do this, it would allow for some interesting coding techniques. One could write utility functions, like the new-ish ".bind()" method on the Function prototype, so that the function returned would be able to check for certain special variables in the closure scope, for debugging or logging or other purposes. Thus services that manufacture functions could do some more "powerful" things based on the nature of the client environment. (I don't know of a language that would allow that.)

What are the benefits of a closure, and when are they typically used?

I'm a web developer, but lots of folks are looking for slightly more advanced skills and understanding closures seems to be at the forefront of this.
I get the whole "execution context creating a reference to a variable that doesnt ever get destroyed" thing, but really, is this some sort of private or static variable implementation in JavaScript?
They can be good for lots of things, for example, visibility (like private members in traditional OO).
var count = function(num) {
return function(add) {
add = add || 1;
num += add;
return num;
}
}
See it.
My count() can be seeded with a number. When I assign a variable to the return, I can call it with an optional number to add to the internal num (an argument originally, but still part of the scope of the returned function).
This is a pretty good overview.
See also on Stack Overflow
What is a practical use for a closure in JavaScript?
How does a javascript closure work ?
When actually is a closure created?
more...
A closure is a code block with bound variables - it "catches" its variables from their outer context - but it is independent from that same context.
A practical use in javascript is when defining events or callbacks - you declare a closure to be executed on the click of a button, for instance, but this closure can reference variables declared on the caller scope.
jQuery uses closures a lot - btw this is a good link for understanding closures for jQuery: A Graphical Explanation Of Javascript Closures In A jQuery Context.
Hope it helps.
There are many JS books available, but you really should grab a copy of David Flanagan's JavaScript: The Definitive Guide if you really want to learn this (still the best JS reference IMHO). Read the chapter on closures and you'll get a lot more in-depth knowledge than anyone can give you in a reply here.

Categories

Resources