This content originally appeared on Bits and Pieces - Medium and was authored by RAVI SHARMA
Collection of Common Closure Problems in JavaScript
![](https://cdn-images-1.medium.com/max/1024/1*D6xX8GkyJsKHW40QsA9YAQ.png)
In this article I am sharing some of the most common and complicated problems based on JavaScript Closures.
Before moving to solution first take your time and try to solve the problems then verify your solution is correct or not.
Problem 1.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*RHmGrG3iOWx_aviGx_gWsA.png)
Solution
We have function foo that returns an anonymous function. No matter where the function was executed it still remembers and has access to the scope in which it was declared. The returned function has access to inner scope (foo scope) and outer scope (global scope).
Also we have two variable with the same name the variable shadowing occurs. So the output will be 200.
Problem 2.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*nAQLxnfLszZI3crC0aZq-Q.png)
Solution
The anonymous function assigned to the result array have access to the outer scope (global scope) where variable i is stored. Every time when we execute any of that functions we get the value that was assigned to i variable in the last for iteration-the step when the condition wasn’t fulfilled. So the value of i will become 5 and the output will be 5.
Problem 3.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*BygDsMzwzbWovOStfPVIXw.png)
Solution
In each for iteration we create an IIFE function that receives its own copy of i variable’s value and assigns that value to its local x variable. That’s why every time when we execute any of that functions we get the value that was assigned to a local x variable, in this case for result[0] value of x will be 0 that’s why output will be 0.
Problem 4.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*7w53PI6wYHe0cPIInzQb2w.png)
Solution
In the first step, we assign the value 50 to the b1 variable and assign returned function to a variable fn.
var fn = run(50); // b1 = 50
In the next step, we call that function that was returned what causes that b1 variable will be increased by 10.
fn() // b1 = 50 + 10;
In the last step, we call that function again what increases the b1 variable by 10 again.
console.log(fn()); // b1 = 60 +10
As we use closure the b1 variable value isn’t reset with each fn execution.So the output of this code will be 70.
Problem 5.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*QGFUOhVmFbHhVZpOkUxftA.png)
Solution
No matter if we execute a function with a delay it still remembers the scope in which it was declared. The function inside setTimeout has access to lexical scope (run scope) and variable name (Ravi Sharma). So output of this code will be Ravi Sharma.
Problem 6.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*WWacYWtGcQNH1lu9buHExw.png)
Solution
No matter where the function was executed it still remembers and has access to the lexical scope in which it was declared. here slow function has access to inner scope (run scope) and outer scope (global scope). So therefore output will be 20.
Problem 7.
Does this code represents an example of the closure?
![](https://cdn-images-1.medium.com/max/1024/1*RSXwyxfqWYXi5UB1_vVprQ.png)
Solution
What we return from IIFE function is plain object, not a function. A closure is the combination of a function and the lexical environment within which that function was declared. So this is not example of closure.
Problem 8.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*vvsXa3W0MzJLvJckqeMSbg.png)
Solution
This is a simple example of closure. Here inner function fast can access lexical scope variable a and output will be 20.
Problem 9.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*VXn0HuJhTGZzrAa8kO30vA.png)
Solution
Even if we execute a function in the context of a DOM element it still remembers the scope in which it was declared. The onclick handler has access to inner scope(run scope) and it will display value of x is 20.
Problem 10.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*DJLxwjuhbarcYuAGIKud4w.png)
Solution
As we know an inner function has always access to the variables and parameters of its outer function, even after the outer function has returned.
Here also when we call add(10) it will set a to 10. when we call totalSum(5) then value of b become 5. At the end inner function will retain reference of variable a and use its value to perform sum = 10 + 5. So the output will be “Sum of two numbers is 15”
Problem 11.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*tToV1WEuRVQGvdx0UfLVWw.png)
Solution
The goal of the code above is to alert the numbers 0, 1, and 2 each after 1, 1.1, and 1.2 seconds, respectively, but in this case there is some issue with JavaScript closures. Due to synchronous nature of JS it will not wait for setTimeout for 1ms and will execute for loop for 3 times, at that stage value of i will become 3. After 1ms inner function will try to get value of i which is in lexical scope so it will use 3. So the output will be 3,3,3.
To avoid this issue see the next problem.
Problem 12.
What will the following code output to the console?
![](https://cdn-images-1.medium.com/max/1024/1*c4UtNGcOJWGfheslMwAj_Q.png)
Solution
Here we have used let variable inside the for loop. So the inner function will contains new i for each iteration and it will be different. So the output of this code will be 0,1,2.
Thank you for reading. I hope you have found this useful. If so, be sure to like and share.
If interested subscribe to my YouTube channel: “JavaScript Centric” https://www.youtube.com/c/JavaScriptCentric
Thanks for reading!
Build composable applications
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →
![](https://cdn-images-1.medium.com/max/800/1*ctBUj-lpq4PZpMcEF-qB7w.gif)
Learn More
- How We Build Micro Frontends
- How we Build a Component Design System
- The Composable Enterprise: A Guide
- 7 Tools for Faster Frontend Development in 2022
Common Closure Problems in JavaScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by RAVI SHARMA
![](https://www.radiofree.org/wp-content/plugins/print-app/icon.jpg)
RAVI SHARMA | Sciencx (2022-03-27T12:21:01+00:00) Common Closure Problems in JavaScript. Retrieved from https://www.scien.cx/2022/03/27/common-closure-problems-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.