Javascript Closure

Javascript Closure seems BIG deal but its not its just simlple function. Some time function is having some variable or method inside it.

function closureFunction() {
    console.log('Hello, CodeRecharge.')
}

// this `closureFunction` is called clouser in short its just a function
console.log(closureFunction); 

// output
/*
ƒ closureFunction() {
    console.log('Hello, CodeRecharge.')
}
*/

Clouser/Function with variable and method inside it

function closureFunction() {
    let name = 'CodeRecharge';
    function anotherFunction() {
        console.log(`Hello, ${name}.`)
    }
    return anotherFunction;
}

const refOfAnotherFn = closureFunction(); 

refOfAnotherFn();

// output
// Hello, CodeRecharge.

Note: Here name is private variable you can not access it without using anotherFunction function.

Popular Javascript Closure articles and code snippets

Related Articles

js interview questions