from Hacker News

JavaScript closures vs. anonymous functions

by hammerha on 3/18/13, 7:08 AM with 18 comments

  • by tomp on 3/18/13, 8:30 AM

    Wow, that was needlessly complicated and (IMO) incorrect.

    Any function that has free variables that are not global variables is a closure. Another way to think about it: any function that cannot be implemented in C is a closure.

    So, in these examples, the inner functions are closures, the outer ones are not, but only because the outer ones are used in a global scope. If you enclosed everything in another function, then also the outer functions would be closures.

  • by AlexanderDhoore on 3/18/13, 9:54 AM

    Chapter 3 in "Structure and Interpretation of Computer Programs" (SICP) explains the environment model to evaluate scheme. That's exactly what you need to understand javascript closures.

    Only read the 3.2 part, it's not long: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html...

  • by just2n on 3/18/13, 8:42 AM

    This question comes up so often both in IRC support channels and on SO that I don't understand why this wasn't closed as a duplicate.

    The accepted answer also overcomplicates what could be a very simple answer.

    In a quick Google, I found this. Asked in '08, not '12: http://stackoverflow.com/questions/111102/how-do-javascript-...

  • by lhnz on 3/18/13, 1:14 PM

    The second answer states it best: "They all use closure(even in the 1st example)."

    If you're accessing a local variable from a different function scope than it was created in then you are using a closure - there is nothing special about how it was defined, this is the only distinction.

  • by hayksaakian on 3/18/13, 7:38 AM

    What are the applications of this distinction?