Will a simple function declaration form a closure in JavaScript?

javascript

Solution

Yes, it forms a closure.

A closure is the combination of a function reference and the environment where the function is created. The code in the function will always have access to any variables defined in the scope where the function is created, no matter how the function is called.

Example; the function `f` will always use the variable `x` even if it is called in a scope where `x` isn't reachable:

function container() {

  var x = 42;

  function f() {
    document.write(x);
  }

  return f;

}

var func = container();
func(); // displays 42
//document.write(x); // would give an error as x is not in scope

Problem

Will the following code form a closure? ``` function f() {} ``` Does where this function is defined affect the answer?

Original source

Related problems