[sign in]

What's a Closure?

  1. What's a Closure?
  2. Variables and Values
  3. Defining Functions
  4. Side Effects
  5. Functions are Values
  6. Returning Functions
  7. Function Scope
  8. Nested Functions
  9. Stateful Closures
  10. Private Data
  11. Asynchronous Callbacks
  12. Continuation Passing

Function Scope

Many languages have block scope, which means that variables declared at the start of a block like an if or a for loop are valid within that block. JavaScript is a bit different, all variables have function scope.

This means that all the variables declared in a function are available everywhere in the function. Here's an example that shows how this can be a little surprising.

Does cow get turned into "glue" when you call f(2)? No, cow is safe in the above code because the var cow declaration inside the if block applies to the entire function. It means that cow is a local variable for the entire function.

To satisfy your morbid bovine curiosities, here is the version that does turn cow into glue.

Because of this surprising behavior, when you write functions you should always declare all your variables right at the start so you don't get confused. Here's an example that declares a few variables the right way.

Define a function named callFunc that takes one argument, a function f. It should return an array containing the values f(0), f(0), f(1), f(1). You can only call f twice.


about news main