JavaScript Closures: Unlock Their Power for Better Code
A Clear Explanation of JavaScript Closures
JavaScript closures are a powerful feature, but they can sometimes be a bit tricky to grasp. Even experienced developers might not use them frequently or fully understand their potential. Personally, while I've worked with JavaScript throughout my career, I haven't always had the opportunity to dive deep into closures. However, I've recently been exploring their value, and they're a technique worth mastering.
So, what exactly *is* a closure? A good working definition is that closure in JavaScript is a function that has access to variables from its surrounding (lexical) scope, even after the outer function has returned. This allows you to create functions that "remember" and maintain access to values from their creation environment.
function outerFunction() {
var x = 10;
function innerFunction() {
return x;
}
return innerFunction;
}
var inner = outerFunction();
console.log(inner());
Here is an example of a closure. The outer function outerFunction() creates a variable x and a function innerFunction(). The inner function innerFunction() returns the value of the variable x. The outer function then returns the inner function innerFunction().
Next inner function innerFunction() is then assigned to the variable inner. When the variable inner is called, it returns the value of the variable x, even though the outer function outerFunction() has already returned.
In a moment we can cover lexical scoping. First, let’s understand why we need them. Plus some disadvantages too.
Pros and Cons
Closures can help hide the encapsulation details. Like Java’s private variables and functions, this allows us to control access. The downside of this is closures take up more memory. These items can not be garbage collected. Lastly, it can slow down execution. Deepak Mankotia explores this more in-depth.
Lexical Scoping
The term lexical scoping refers to where the variable is defined. Along with that where it can be referenced or not.
let x = 10
let myFunc = function (){
let y = 20;
console.log("x and y is accessible (outer):", x, y);
let insideFunc= function (){
let z = 30;
console.log("x and y and z is accessible (inner):", x, y, z);
}
insideFunc();
return;
}
myFunc();
console.log("only x is accessible (global):", a);
In this example, insideFunc is defined within the myFunc. In this case, myFunc is its parent. The child function is lexically bound by that of the parent function. JavaScript Closures are a form of Lexical Scoping.
JavaScript Closures are powerful tools. They have some distinct values. It allows you to encapsulate details but, it can slow down your execution time. Consider whether the risks and rewards work for your application.