Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Member-only story

JavaScript: Closure

--

Press enter or click to view image in full size
Photo by Mohammad Rahmani on Unsplash

One of the most interesting yet mind-boggling concepts in JavaScript would be closure. Like it or not, many people stumble upon this concept and find it difficult, especially during interviews. Most of the time, the theory around closures is easy to read. However, when you are given an out of box problem statement, you are likely to stumble. Why? You may not have understood the true meaning and significance of closures.

In this post, I would like to share my understanding of what a closure is and why it is used.

Long Story Told Short

Firstly, I strongly believe closure is nothing but a function.

When a function is paired with its reference in the outer scope (alias lexical environment), it becomes a closure.

What is a lexical environment? It is nothing but an execution context, which appears like a stack frame. In a lexical environment, all local variable names and values are mapped.

JavaScript makes use of the lexical environment, all the time. Every function has a reference in the lexical environment. When a function gets invoked, the reference of the function is used to build the actual execution context. As a result, all lines of code inside the function will be able to see the actual value of variables outside. Irrespective of where, and when the function is…

--

--

D Bharathi
D Bharathi

Written by D Bharathi

A Grad from Anna University, with Sound Frontend Skills.

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.