Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a simple function declaration form a closure in JavaScript?

Tags:

javascript

Will the following code form a closure?

function f() {}

Does where this function is defined affect the answer?

like image 206
Ben Aston Avatar asked Sep 28 '22 16:09

Ben Aston


1 Answers

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
like image 138
Guffa Avatar answered Oct 03 '22 00:10

Guffa