Closure in JavaScript are most confusing term, but actually it is most powerful concept of JavaScript. Closure occurs in JavaScript because of functional level scoping. Function inside function can use members of outer function (parent function).
I would like to write 2 most important
- The context of an inner function includes the scope of the outer function.
- An inner function enjoy that context even after the parent functions have returned.
Let’s discuss one problem scenario, suppose we have one button on the page and now we need how many times button is clicked, we need the count. One simple way of implementation is: use one global variable and increment that variable on button click. This is easy but Global variables are not good to use, because same variable name might be present in the application. It is never recommended to use global variable in JavaScript. One good solution to this is to use functional level scoping of JavaScript and create Closure. Closure in JavaScript are caused due to function level scoping.
Below is one example of closure which is used to get one incremented number every time.
var getCount = (function () { var counter = 0; // parent function variable which is accessible in child function return function () { return ++counter; }; })(); // self executing function
The output of this function when called will be as shown below:
You also like to know about:
- Do you know what happens when you hit url www.goolge.com?
- Know about Debouncing & Throttling
- AngularJS advanced trick and techniques
- Restrict input to allow only required value (jQuery plugin for input type validation)
- Spread operator or Rest parameter or Ellipsis in JavaScript
- Why call and apply two methods available in JavaScript
- Automatic Form Input Validation for complete site
- Number of ways you can create function in JavaScript +what are they called
- JavaScript Native objects
- How to Create private function in JavaScript
- functions as first class object in JavaScript
- Object Oriented concept in JavaScript
- Advanced JavaScript questions
- One good way to declare Global Variables in JavaScript
- how to align elements in a row with equal space around
- Closures in JavaScript
- AJAX call in AngularJS for cross domain service using JSONP
- Cross Site Scripting in WCF Web Service. How to use AJAX in JavaScript to Get/Consume JSON from WCF in C#
- How to add AngularJS in rails application
- Git configuration all about
- Pass XML file in stored procedure as a input parameter from C#
- XML Parser in SQL Server (T-SQL), How to parse XML in SQL
- Wish your friend with your own words and love
- Create Message in Hindi by typing in Hinglish
- Convert Multiline Text Into Single Line for HTML page