Contents

About closure

   Aug 3, 2023     1 min read

This post is about Closure.

As you study JS, you’ll come across a lot of functional programming. There are two concepts that come up again and again in functional programming: first-class functions and closures.

Today we’re going to talk about closures.

What is Gradle?

Gradle is a modern build automation system and build tool. It is used not only for Android projects, but also for projects on various platforms and languages. It can build projects written in different languages like Java, Kotlin, Groovy, etc. and is used to organize and manage projects through build scripts.

Now that you know what Gradle is and what it does, let’s take a look at its main features.

What is a closure?

A closure is a combination of a function and information about the environment when the function is declared. In other words, closure is the property that local variables inside a function do not disappear when the function finishes executing.

Features

An important characteristic of a closure is that the inner function can access the outer function’s variables, and it remembers their state even after the outer function exits.

Example

function makeAdder(x) {
  return function (y) {
    return x + y;
  };
}

let add5 = makeAdder(5);
console.log(add5(2)); // output: 7

In the above example, makeAdder returns a closure. The variable named add5 stores the function returned by the makeAdder function. This function has access to the makeAdder function’s parameter x, and it remembers the state of x even after the makeAdder function has finished executing. So when we run add5(2), it outputs 7, which is the result of adding the previously stored value of x, 5, to the new input, 2.

Conclusion

These properties of closures can be useful for hiding and encapsulating data.