How to use closure in JavaScript

3 Answers

0 votes
function makeAdder(x) {
    // This inner function forms a closure.
    // It "remembers" the value of x even after makeAdder returns.
    return function(y) {
        return x + y;
    };
}

const add10 = makeAdder(10); // x = 10 is captured
const result = add10(20); // y = 20

console.log(result);



/*
run:

30

*/

 



answered Jun 2 by avibootz
edited Jun 2 by avibootz
0 votes
// Closures capture variables by reference

let counter = 0;

const inc = () => {
    counter++;   // closure captures "counter"
};

inc();
inc();

console.log(counter);


/*
run:

2

*/

 



answered Jun 2 by avibootz
0 votes
// Closures inside loops

const funcs = [];

for (let i = 0; i < 3; i++) {
    funcs.push(() => console.log(i));
}

funcs[0]();
funcs[1]();
funcs[2]();



/*
run:

0
1
2

*/

 



answered Jun 2 by avibootz

Related questions

4 answers 38 views
4 answers 50 views
4 answers 42 views
5 answers 45 views
4 answers 43 views
3 answers 40 views
...