Loren Riesenfeld

Closures in Javascript

A closure in javascript is when a function "remembers" and continues to access the variables in its lexical scope even when the function is executed outside of that lexical scope.

Here's an example:

function foo() {
  var bar = 'bar'

  return function() {
    console.log(bar)
  }
}

function bam() {
  foo()() // "bar"
}

bam()

The inner function that's being returned from the foo function in a sense "closed" over the bar variable and prevented it from being garbage collected, allowing the bam function to access it.

I guess a shorter way of describing closure would be: how to access a variable outside of its lexical scope, although I'm sure that loses some nuance and Kyle Simpson would probably role his eyes at me.