Closures in JavaScript [Easily explained]

Closures in JavaScript [Easily explained]

ยท

2 min read

Closures in JavaScript,

a concept you would never skip before going for a JS interview. If you don't know what this term means, let me brief you on the same.

A proper definition of closure could look something like this:

A Closure in JavaScript is a function, bundled together with its lexical scope.

Simple, yet confusing.What is a lexical scope you ask?

Lexical scope simply means that in a nested group of functions (functions inside functions), the inner functions can access data (variables, functions, objects, etc.) of their parent scope.

That is why in JavaScript, one can access variables from outside the function, unlike other programming languages.

So, if we now look at what closure's definition makes sense:

A closure is an inner function that always has access to the variables and parameters of its outer function.

Also note that even if the outer function is completely executed, or the inner function is executed in a completely different context, the inner function can still access the outside parameters and variables because JS preserves these outside functions' data for inner functions. For example:

function outerFunction() {
    let a = 10;
    return function innerFunction() {
        console.log(a);
    }
}

let returnFunction = outerFunction(); 

// if we think logically here, the outerFunction has been completely executed, hence, the variable "a" would also no longer exist for innerFunction to log. 

returnFunction(); // will display 10
// because of closure, the innerFunction preserved the resources from its lexical scope.

So if you still wonder why closures are so important, remember that not all languages let you preserve/remember values from the lexical scope, even if the outer one is executed completely.

But in JS, our functions get bundled up with outer variables and other resources, which is what Closure exactly is :)

If you wish to learn this concept much more clearly with an example, just check out this amazing article by Dmitri Pavlutin on the same.

Happy coding :)

#10daysofJSfundamentals (DAY 10 ๐ŸŽ‰)