DEV Community

Cover image for Closure in javascript
Chandra Prakash Pal
Chandra Prakash Pal

Posted on

Closure in javascript

An important topic in JavaScript is the concept of closures. When a function is created, it has access to a reference to all the variables declared around it, also known as it's lexical environment. The combination of the function and its enviroment is called a closure. This is a powerful and often used feature of the language.

function createAdder(a) {
  function f(b) {
    const sum = a + b;
    return sum;
  }
  return f;
}
const f = createAdder(3);
console.log(f(4)); // 7
another example
function createAdder(a){
    return function f1(b){
        return function f2(c){
            const sum=a+b+c;
            return sum;
        }

    }
}

const f=createAdder(3);
const f1=f(4);
const f2=f1(5)
console.log(f2)//12
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay