Closures in Javascript PART-1

Photo by Billy Huynh on Unsplash

Closures in Javascript PART-1

DISCLAIMER: I've written this blog to share with others what I've understood after going through several blogs, articles, videos, etc. So the following written blog might contain some ideas & language influenced by those.


Overview

Closures are one of the most asked interview topics & are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

Definition

  • A closure is a function bundled together with it's lexical environment.
  • In simple words a closure gives you access from an outer function's scope from an inner function.
  • In Javascript, a closure is created every time a function is created, at function creation time.

Lexical Scoping

The following is an example of lexical scoping, where getName() has 2 local variables firstName & lastName.
It also has a nested method which is accessing these variables of it's other function.
carbon JSFiddle Link Lexical Scoping describes how a parser resolves variable names when functions are nested.

Closures

Now what happens if we return this nested method and call it from outside?
carbon (1) JS Fiddle Link It works exactly the same as in previous example. The catch here is when we return the function, it is returned along with its lexical environment. The lexical environment of the inner function getFullName consists of any local variables that were in-scope at the time when closure was created.

References:

  1. developer.mozilla.org/en-US/docs/Web/JavaSc..
  2. javascript.info/closure
  3. youtube.com/watch?v=qikxEIxsXco
  4. youtube.com/watch?v=71AtaJpJHw0