Closure In JavaScript

Rhea RB
2 min readNov 19, 2022

--

What is a closure ?

A closure is a function in Javascript that has access to its outer function scope even after the outer fucntionhas returned. This means a closure can remember and access variables and arguements of its out function even after the function has finished.

Before we dive into closure Lets first understand Lexical scope.

Lexical Scope
A lexical or static scope in Javascript refers to the accessibility of the variables, functions and object based on their physical location in the source code.
Example:

The inner function can access the variables defined in its own scope, the outer function’s scope and the global scope. So a scope chain would look like this,

Notice that inner function is surrounded by the lexical scope of outer function which is surrounded by the global scope. This is the reason for the inner function being able to access the variables defined in outer and global scope.

Closure Example

In the code, We are calling myfunction, which returns inner function myName and stores the inner function in rhea variable. When we call function rhea which is referencing the myName function, the name Rhea is printed in console. But we do not have any variable named name in myName, this function can access the variable of its outer function myfunction even after the function has returned.
The function myName is actually a closure.

If you liked my blog please do follow me : Rhea RB

Thank you for reading ! Happy Coding !!

--

--

Rhea RB
Rhea RB

Written by Rhea RB

Hello ! I am a senior software engineer, passionate about tech and product.

No responses yet