A Closure is a combination of function and lexical environment where this function was declared. The environment may consist of both local variables declared in the body of a function and global ones declared outside of the function. To put it in an equation, Closure equals function plus lexical environment (for instance, local variables, global variables, outer functions) within which that function was declared.

If you keep your mind open and have no prejudices, at the end of this article we’ll grasp the idea and practical implementation of closures.

The below example shows that the inner anonymous function has access to the local variable _double _out of its scope (lexical scope). We bind this function to different variables outside of this scope and each time we call them, we can pass different values as arguments. As soon as the anonymous function has access to the inner variable double, it can now take both this variable value and passed the argument and make simple calculations (val * double).

function simpleDoubler(){
    let double = 2; // local variable of lexical environment
    return function (val){
       return val * double;
 }
}
let doubleFour = simpleDoubler();
let doubleTen = simpleDoubler();
console.log(doubleFour(4)); // 8
console.log(doubleTen(10)); // 20

Each time, when we console log _simpleDoubler _function and pass the desired integer to be doubled, it performs these operations written in the body of the function. Another implementation to consider:

let colorChanger = (function() {
    return function change(color) {
console.log({color});
}})();
let red = colorChanger('red');
let green = colorChanger('green');
let orange = colorChanger('orange');

#closures-functions #programming #javascript

JavaScript Closures
1.20 GEEK