I started learning about functional programming and I'm a bit confusing about it.
My question is: is Java lambdas equivalent to JavaScript closures? If not, what is the difference between them?
They are "slightly different" and also "roughly equivalent".
tldr; a Java lambda that access an outer-scoped variable1 is also a closure; and a JavaScript "closure" that does not access an outer-scope variable is not strictly a closure (and can be more precisely called an anonymous function2).
In JavaScript, a closure generally implies "being able to re-assign variables in the outer scope" - however, having access to or "closing over / binding" a variable is sufficient for an anonymous function to be a closure3.
Java lambda's requires that all variables from the outer scope accessed in a lambda are effectively final which means they cannot be re-assigned.
1The rule is that a [Java] lambda expression can only access local variables from an enclosing scope that are effectively final. An effectively final variable is never modified—it either is or could be declared as final - http://www.informit.com/articles/article.aspx?p=2303960
However, since a Java lambda can capture a read-only variable binding to mutable objects, it is possible for a Java lambda to indirectly modify state in the outer context and can thus emulate the ability to "re-assign" values.
2In computer science, a closure is a function that has an environment of its own. Inside this environment, there is at least one bound variable [and] anonymous functions are sometimes wrongly called closures. This is probably because most languages [eg. JavaScript] that have anonymous functions also have closures and it's common for programmers to learn about both at the same time. - https://simple.wikipedia.org/wiki/Closure_(computer_science)
Java also has different semantics on this inside a lambda vs a JS anon-function / closure; also see JavaScript "arrow functions" which have different rules than traditional anonymous functions on how this behaves.
3 Trivial argument:
No, they are not equivalent. One has to do with syntax and the other with memory.
Lambdas are a short-hand syntax for declaring anonymous code structures.
Closures are when a nested function (named or not) holds a reference to a variable from a function in an outer scope. That, in and of itself isn't really an issue. But, when the nested function persists longer than the outer scoped variable, the variable won't be garbage collected when the outer scope terminates. That's when closures become either very powerful or very annoying. It all depends on if you are intentionally using them or not. Closures can allow for shared access to private data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With