A Real time Example of JavaScript closure

JavaScript closures are a powerful tool that can be used to create dynamic and responsive web applications. In this article, we'll take a look at a real-time example of how to use closures to create a simple countdown timer.

Hey ! how are you doing? Today I am going to tell you a closure story. It’s pretty interesting and easy to remember. We all know in JavaScript it’s a very common question asked several times , what is closure? can you give a real time example of that?

In the top picture you can see one lady is buying oranges from a outside trolley. Imagine it’s an outer function where oranges are a variable. That lady brings those oranges to home . Now you think she is inside inner function. Now she wants to have a glass of orange juice . So she cuts few oranges and squash it and pour it in a jar. In this process she is returning a juice served in a glass closure within buying oranges.

Always remember closure captures variables from lexical scope.

Now if I write the whole process programmatically how it will look?

function buyOrange () {

let fruit = “oranges”; // lexical scope

function prepareJuice() {

debugger

Console.log (“Let’s Squash:” +fruit+ “& juice is ready”); // closure

}

return prepareJuice;

}

Const serveJuiceInAGlass = buyOrange();

serveJuiceInAGlass();

If you run this code in jsfiddle or codepen or anything else you can see on the console that inside scope closure is buyOrange

Is not it pretty simple?

Now if there’s a different scenario, let’s see how it will behave. This time one of her friend suddenly appeared to surprise her. She was so happy to see her friend. She asked her friend politely would you like to have some juice?

Her friend, sure ! This time she wants her friends to choose a flavour for the juice. Then she started gossiping after few minutes she made a juice of her friends choice and served her.

Now let’s create function.

function prepareJuice (flavour) {

return function () {

debugger

setTimeout(_ => console.log(‘Made a ${flavour} Juice!),1000)

}

}

Const serveJuiceLater = prepareJuice (‘Water Melon’);

serveJuiceLater();

Here Closure (prepareJuice)

Closure Advantages

  • The scope is not at the block level but at the function level
  • Many functions are event driven/asynchronous
  • Encapsulation through information hiding

Things to remember

  1. To control side effects
  2. To create private variable.

#javascript #js 

A Real time Example of JavaScript closure
38.50 GEEK