settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Give an example of closure in JavaScript?

+3 votes
Can you please give an example of a closure in Javascript? I need to understand the closure....
asked in JavaScript category by user eiorgert

3 Answers

+2 votes

Closure == state maintained (closed) inside a function. Hidden from the outside world

Example: counter with closures:

function counterClosure() {
    let counter = 0;

    function getNextCount() {
        console.log(++counter);
    }

    return getNextCount;
}

or with IIFE (see here)

let counter = (function counterClosure() {
    let counter = 0;

    function getNextCount() {
        console.log(++counter);
    }

    return getNextCount;
})();

counter();

 

answered by user hues
+1 vote

Example of closure in JS with the Fibonacci numbers (function that when called, returns the next Fibonacci number, starting at 0, 1):

let fib = (function () {
    let f0 = 0;
    let f1 = 1;

    return function () {
        let oldf0 = f0;
        let oldf1 = f1;

        f0 = oldf1;
        f1 = oldf0 + oldf1;

        return f0;
    }
})();

console.log(fib());//->1
console.log(fib());//->1
console.log(fib());//->2
console.log(fib());//->3
console.log(fib());//->5
console.log(fib());//->8
console.log(fib());//->13

 

answered by user icabe
0 votes

Another example with "Module" Pattern (with Closure):

let module = (function () {
    let count = 0;

    return {
        increase: (num) => count += num,
        decrease: (num) => count -= num,
        value: () => count
    };
})();

 

answered by user Jolie Ann
...