In this article, we will learn about "Closures" and how they actually work in JavaScript. A closure is basically a composition of a function that contains a reference to its surrounding state (also known as lexical environment).
In JavaScript, a closure is created basically every time a function is created at runtime. In other words, a closure is just a fancy name that remembers something external that is used internally.
Let us understand JavaScript closures through some examples -
In the following example, we will declare a closure that will ultimately be accessible from an external function External variable tagLine
After using the external variable in the innermost function, this specific closure will help the user to remind the tagLine every time the external function is called.
#Filename: index.html
<!DOCTYPE html> <html> <head> <title> Closures in Javascript </title> </head> <body> <h1 style="color: green;"> Welcome To Tutorials Point </h1> <button type="button" onclick="init()"> Click here!!! </button> <p id="demo"></p> <script> function init() { var tagLine = "Start your Learning journey now"; function display() { // display() is the inner function, a closure alert(tagLine); // use variable declared in the parent function } display(); } </script> </body> </html>
This will produce the following results.
In the following example, we use nested closures to call two functions and display the output of the same function.
#File name: index.html
<!DOCTYPE html> <html> <head> <title> Closures in Javascript </title> </head> <body> <h1 style="color: green;"> Welcome To Tutorials Point </h1> <button type="button" onclick=" Counter()"> Click Me! </button> <p id="demo1"></p> <p id="demo2"></p> <script> function Counter() { var counter = 0; function outerfunction() { counter += 1; document.getElementById("demo1").innerHTML = "Outer Counter called = " + counter +" from Outer Function " ; function innerfunction() { counter += 1; document.getElementById("demo2").innerHTML = "Inner Counter called = " + counter +" from Inner Function "; }; innerfunction(); }; outerfunction(); }; </script> </body> </html>
The above is the detailed content of How do closures work in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!