Closures in Javascript PART-1

shiv1998

Shivaansh Agarwal

Posted on December 14, 2020

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. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
  2. https://javascript.info/closure
  3. https://www.youtube.com/watch?v=qikxEIxsXco
  4. https://www.youtube.com/watch?v=71AtaJpJHw0
πŸ’– πŸ’ͺ πŸ™… 🚩
shiv1998
Shivaansh Agarwal

Posted on December 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related