Member-only story
10 JavaScript Closure Challenges Explained With Diagrams
Cracking the interview questions

Closures are one of the core concepts in functional programming, and it is must-have knowledge for every JavaScript developer. Here I have prepared 10 closure challenges, many of which are frequently asked in interviews.
Are you ready, challenger? Enjoy this journey!
Each challenge is a code snippet, and you need to say what the output of this code will be.
1. Scope
Before talking about closures, we must understand the concept of scope, which is the cornerstone of understanding closures.
What is the output of this code snippet?
It is very simple. I believe that all challengers know that the output result is 10
.
- By default, there is a global scope.
- A local scope is created by a function or a code block.

When console.log(a)
is executed, the JavaScript engine will first look for a
in the local scope created by the function foo
. When the JavaScript engine can’t find a
, it will try to find a
in its outer scope, which is the global scope. Then it turns out that the value of a
is 10.