Need Closure?

Saima Rahman
2 min readJul 8, 2020

Well, we are talking about a Javascript feature here!

Intro picture

A Closure is a simple concept that returns a function inside another function. Also, remember functions are first-class citizens meaning one function can be inside another function. Functions in closure come with a backpack!

  • Whatever the outer functions will have, the inner function carries it in the backpack, e.g variables, or any parameters.
  • It knows that it has been run previously.

Whenever the inner function is called, it will always look for variables in the backpack or also known as Persistent Lexical Scope ( The scope of the functions depends on where it has been declared not executed). This is the typical behavior of functions in javascript.

Let us look at this example:

Write a function that will increment counter by one and when it is called again it will be incremented againfunction outer(){
let counter = 0; //backpack analogy
function increment(){
let num = 1
counter = counter + num
return counter
}
return increment; //function declaration not invocation
}
let innerFunc = outer()
console.log(innerFunc())//1
console.log(innerFunc())//2
console.log(innerFunc())//3

In the above example, we are setting the variable “counter” in the outer function because the memory has to be stored in the outer function. Remember the backpack analogy? Things in the outer functions will be stored in the inner function’s backpack. Now the inner function will know how many times it has been run and it has access to the variable counter. Notice we are returning the inner function as a function declaration, not invocation.

Let us do the same thing, with regular function, it will make more sense now:

function increment(){
let counter = 0
let num = 1
counter = counter + num
return counter
}
console.log(increment());// 1
console.log(increment());// 1
console.log(increment());// 1

SEE! Does not matter how many times you call this function, it will print one, because a regular function does not have a memory of previous runs. Whereas in closure, whenever the function was called, the counter was incremented by one. Please try this in a text editor and see the difference!

Please do try this problem by yourself:

Write a function that we can only call ONCE, if you run it first time it will print the timestamp with the label first run ,
if you try run it again it should not do anyting.

If after several attempts, you need help with the problem, message me on Instagram @muslimaTechies. Happy Coding!

--

--