DEV Community

Nashmeyah
Nashmeyah

Posted on

Closures

What is a closure?

"A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time." (MDN Web Docs, online)

In other words, a closures control what is and isn't in a scope for a function. A closure gives you access to an outer functions scope from within the function you are currently working in. The inner function will have access to the variables and objects from the outer functions scope.

Some examples of simple closures.

function increment() {

let i = 0;

  return function() {

    return i++;

  }

}

let addUp = increment();
//addUp() 0
//addUp() 1
//addUp() 2
Enter fullscreen mode Exit fullscreen mode

In this example, out inner function is pulling data from outside its scope and accessing a variable from the outer function.

Here is another example.

let num = 5;

const addTo = function(){
  let inner = 2;
  return num + inner;
}
console.log(addTo());
Enter fullscreen mode Exit fullscreen mode

In this example, 1 function is accessing a global variable from within the functions scope.

I hope you enjoyed this blog, have a wonderful day

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more