1. Overview

In this tutorial, we’re going to learn about closures, one of the most powerful features of many programming languages. But before diving into that, let’s have a brief overview of variable scopes and scope chain.

2. Variable Scopes

To begin with, by variable scope we mean the place where this variable is visible and available for us to use in the code. We identify the following scopes: Global Scope and Local Scope

2.1. Global Scope

A variable that is declared outside a function is defined as global and can be accessed from anywhere in the application:

var foo = 1;

function bar() {
    print(foo);
}
  
print(foo);

2.2. Local or Function Scope

When a variable is declared inside a function, it has a local or function scope, meaning that it’s available for use only within the function and we’ll get an error if we try to access it outside the function:

function bar() {
    var foo = 1;
    print(foo); // prints 1
}

print(foo); // error: foo is not defined
bar(); // prints 1

3. Closure

In many programming languages, functions can return functions. And when a function returns a function, the returning function keeps a reference to all the variables that it needs to execute, which are declared in the parent function.

That’s exactly what a closure is. It is a bucket of references to variables a function needs to execute which are declared outside its scope. 

For example:

function foo() {
    var a = 10; // outer scope
    
    return function bar() {
        var b = 10; // inner scope
        print(a + b); 
    } 
}
  
foo(); // prints 20

function foo(param) {
    return function bar() {
        var b = 10; // inner scope
        print(param + b); 
    } 
}

var anotherWayToCall = foo(10); // this returns a function
anotherWayToCall(); // prints 20

4. Conclusion

In this quick article, we had a look at the concept of closures – one of the core concepts in most programming languages and certainly one of the most important topics in preparing for an interview.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Davorin
Davorin
5 months ago

Probably the simplest explanation ever, much appreciated.
Please expand with Java examples in one of the forthcoming articles. Thanks.

Loredana Crusoveanu
Loredana Crusoveanu
4 months ago
Reply to  Davorin

Hi Davorin,

Thanks for the feedback. The closest equivalent to closures in Java would be lambdas: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#accessing-local-variables, or anonymous inner classes: https://www.baeldung.com/java-anonymous-classes