Scope and Closure in JavaScript

Scope controls the visibility, usability and lifetime of variables and parameters, thereby avoids naming collisions and provides memory management.

JavaScript has Function Scope which means the variables and parameters defined in a function are visible anywhere within that function but not visible outside of that function and cannot be accessed. A variable declared using the var keyword in a function becomes a Local variable or a Private variable. Global variables declared outside the function are accessible anywhere. Any variable declared inside a function without a var keyword becomes a Global variable.

To access the Private variables of a function outside its scope, we need Privileged methods or Inner functions of the objects.

A Closure is this inner function or privileged method, which has access to the variables and parameters of its outer function. A Closure has access to its own variables, its outer functions variables and global variables, with exception of this and its outer function’s arguments.

closure

In the above code, the outer function bookInfo returns the inner function author.

closure

bookInfo function returns an object which contains a method author and that method has the privilege of access to the variable preText and parameters title and year, even after its outer function is returned.

Closures only store a reference to its containing functions variables, not the values themselves. So they have the updated values of their outer functions. But it makes them prone to bugs especially when a variable’s value changes in loop. To avoid this, a helper function can be created outside the loop that binds to the variable, and returns the value of the variable for every iteration, instead of returning the containing function itself.