What is the difference between a closure and an anonymous function in JavaScript
3 Answers
The closure mechanism applies to all JavaScript functions, whether anonymous or not.
I think confusion between the two concepts comes from use of the term "closure" where an author has said something like "the following code creates a closure" and then given an example that happens to use an anonymous function. In such instances typically the closure mechanism is what is important to make the particular piece of code work as intended, while use of an anonymous function rather than a named function just happens to be a convenient way to code it. People reading such examples and seeing "closure" for the first time then misinterpret the term and go on to use it incorrectly in their own Stack Overflow or blog posts and so the confusion spreads.
1 Comment
A closure is an expression relying on a namespace reference in which variables are resolved (a context). An anonymous function is one way to form a closure in Javascript - a named function is another.
There is some discussion about the ability to form closures with non-function blocks, but the current standards specify no such.
http://jibbering.com/faq/notes/closures/ is a pretty good description.
3 Comments
let introduced in JavaScript 1.7 (see more here). From the documentation: "The let statement provides a way to associate values with variables within the scope of a block, without affecting the values of like-named variables outside the block.".A closure is a function that has captured its environment (the variables that it has access to)
It can be created both from an anonymous and as from named function.
And an anonymous function differs from a named function mainly that it's declaration does not get hoisted to top of the scope.
foo. Even thoughfoois inside the outer function, but not the inner function, the inner function can still accessfoo. This is because the inner func creates a "closure" over the variable environment of the outer. So a "closure" is this phenomenon of nested variable environments being able to access the variables of the environments that contain it.