Home >Web Front-end >JS Tutorial >Understanding JavaScript closures: variables, functions, and scope.
“Javascript closures are a fundamental concept in programming, enabling functions to access and manipulate variables from surrounding scopes. This powerful technique allows for data encapsulation, context preservation, and efficient memory management. Understanding Javascript closures is crucial for developing robust, scalable, and maintainable applications. In this article, we will look into the complexity of this concept, exploring variables, functions, and scope to master this essential Javascript concept.”.
Now let's see what a closure in Javascript is. I will like to define this in three ways: in a simple and concise way, in a technical and detailed definition, and in a conceptual and analogous definition.
“A closure is a/are channel(s) through which function inside another function have access to its own scope and the scope of its outer function(s), even when the outer function(s) have returned.”.
“A closure can also be referred to as a self-contained function that maintains a reference to its surrounding lexical scope, allowing it to access and manipulate variables from that scope, even when the function is invoked outside its original context.”.
“A closure is like a room with memory. When a function is created inside another function, it inherits the outer function’s scope, much like a room inherits the features of the building it’s in. Even when the outer function ‘closes’ (returns), the inner function remembers the outer scope, allowing it to access its variables and functions". These definitions highlight different aspects of JavaScript closure.
To buttress the definitions or for better understanding of the subject matter, think of a closure like this. Imagine you have a toy box container where you keep all your favorite toys (the toy box container is our outer function). Now imagine that inside the toy container (outerfunction) you have different toys like cars, dolls, and a robot, among other things. (these are variables or any other function) out of these toys, you have a special toy (inner function) which is the robot. Imagine the robot has special powers through a channel; it can play or connect all the other toys inside the toy box even when the toy box is closed. Imagine that special channel or power to be closure. I hope you get that. Let's see an example of a code to illustrate closure.
<script> function details() { let surName = 'john'; let lastName = 'mercy'; function displayDetails() { return `hey ${surName} ${lastName} you have been registered`; } return displayDetails(); } console.log(details()); </script>
In the code above, the displayDetails is the function or the closure, or better still, referring to the illustration before the code. funtion displayDetails is using the power of closure to access the variables outside it’s scope. Here is the thing. displayDetails is defined inside details, it accesses surName and lastName from the outer scope, and it retains this access even outside its scope. Or, in another way, details create a scope with surName and lastName, displayDetails access this scope, displayDetail returns a string using surName and lastName, and details returns displayDetails’s result. console.log(details()); calls displayDetails, accessing outer scope variables.
The output of this code is hey john mercy, you have been registered
The result is shown below
Now that you understand closure, let's see the benefit of closure in Javascript code writing.
<script> function details() { let surName = 'john'; let lastName = 'mercy'; function displayDetails() { return `hey ${surName} ${lastName} you have been registered`; } return displayDetails(); } console.log(details()); </script>
In the code above, the function Person takes two arguments: name and age, This function creates a new person object. Inside the function, two private variables are declared: privateName and privateAge. These variables are assigned the values passed to the person function ( name and Age). These variables are private because they’re declared with let and aren’t directly accessible outside the Person function. The return objects are also created with three methods. These three methods provide controlled access to private variables. So the Person function creates a closure, allowing the returned object to access private variables. Also the private variables are hidden from external access, providing data protection.
<script> function details() { let surName = 'john'; let lastName = 'mercy'; function displayDetails() { return `hey ${surName} ${lastName} you have been registered`; } return displayDetails(); } console.log(details()); </script>
Here is what happened in the code. We define a function createClickCounter that returns another function. Inside createClickCounter, we declare a variable clickCounter initialized to 0.
The returned function increments clickCounter and updates the text content of clickCounterElement. We call createClickCounter() to create a closure and assign it to the counter variable. We attach the counter function to the button's click event using addEventListener.
The counter function is a closure because it has access to its own scope, has access to the outer function's scope (createClickCounter()), retains the state of clickCounter between function calls.
JavaScript closures empower developers to write efficient, modular, and secure code. By mastering variables, functions, and scope, developers can harness closures full potential. Closures enable data encapsulation, state preservation, and private variables, elevating code quality and maintainability. With this foundational understanding, developers can tackle complex Javascript challenges with confidence. Effective use of closures is essential for scalable, robust, and efficient JavaScript applications.
The above is the detailed content of Understanding JavaScript closures: variables, functions, and scope.. For more information, please follow other related articles on the PHP Chinese website!