DEV Community

Deepa Chaurasia
Deepa Chaurasia

Posted on

2

Closures in Javascript

A closure is a function combined with references to variables define outside of it.

They enclose the function and variable in its environment.

Let's say you're having a function greet

Image description

There's two interesting points to notice here.

  • The retured function from greet can access the word parameter.

  • The returned function maintain the value of word when greetings is called outside scope of word.

The first point can be explained by lexical Scope

Lexical Scope- The returned function can access word before it exists in its outer scope.

The second point because of closures

Closure maintains the variable references ,which allows function to access variables outside of their scope.

Examples of Closures in Javascript

Example 1:

Image description

In the example above, the function numberGenerator creates a local “free” variable num (a number) and checkNumber (a function which prints num to the console).

The function checkNumber doesn’t have any local variables of its own — however, it does have access to the variables within the outer function, numberGenerator, because of a closure.

Therefore, it can use the variable num declared in numberGenerator to successfully log it to the console even after numberGenerator has returned.

Example 2:
In this example we’ll demonstrate that a closure contains any and all local variables that were declared inside the outer enclosing function.

function sayHello() {

Image description

Notice how the variable hello is defined after the anonymous function — but can still access the hello variable. This is because the hello variable has already been defined in the function “scope” at the time of creation, making it available when the anonymous function is finally executed.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post