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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)