Closures and JavaScript

Amarpreet Singh
1 min readSep 18, 2017

--

Being all said in the previous post, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions.

Physically, closure is a record/data structure that stores a function along with it’s environment :a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.

Typically, In a language ,during a function execution, automatic variables(local variables) are allocated memory on a stack and deallocated when the function returns.

In order for a language to support lexically scoped first-class functions, this run time memory allocation model does not work.Rather, Heap allocation is used for closures.

JavaScript has first-class functions and uses closures to implement lexical scoping.In JavaScript, closures are just binding of free variables(not global) of a function.

How it’s done:

In JS, function execution goes through two phases: creation and execution.During creation phase, the compiler parses, does lexical analysis ,optimises the code and based on the analysis, it allocates memory to variables on stack or heap.

I have created few examples of closure in JS, along with comments, which explains the aforesaid things in detail: https://github.com/amarpreetsingh29/algorithms/blob/master/concepts/closures/closure.js

--

--