JavaScript is a language of Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
In an aspiration to write better code, JavaScript provides closure. We’ll understand it now, but before that I'll shift gears to a few other concepts like scope & callback
Scoping
In programming, scoping is the part of a computer program where you bind a variable and its visibility. There are two types of scoping, i.e. lexical and dynamic. JavaScript is based on lexical or static scoping. The functions are lexically rather than dynamically scoped. JavaScript blocks scopes using {}, and a new scope is created when you create a new function.
A quick glance at another concept called callback:
Callback
A callback is basically a function that accepts another function as a parameter, I hope it recalls your memory of higher order functions. At some point, the higher order function can call the function passed as parameter, this is a callback.
The common use of closure we are familiar with is setTimeout function.
Closures
A closure is an inner function that has access to the outer function’s variables. It can access complete chain of variables. Illustration:
Closure function can access own variables, function variables in which it’s created and global variables. See from code perspective now,
- var globalVar = 10;
-
- function localFunction()
- {
- var localFuncVar = 20;
- var closureFnc = function()
- {
- var closureVar = 30;
- console.log(globalVar);
- console.log(localFuncVar);
- console.log(closureVar);
- };
- closureFnc();
- }
I added debugger and checked Stack. We can notice Closure (localFunction) created.
Use of closure
A very popular use case is Module pattern, so it can implement OOPS public, private methods concept. Closure help to emulate this, example:
- var modularpattern = (function()
- {
-
- var sum = 0;
- return
- {
- add: function()
- {
- sum = sum + 1;
- return sum;
- },
- reset: function()
- {
- return sum = 0;
- }
- }
- }());
- console.log(modularpattern.add());
- console.log(modularpattern.add());
- console.log(modularpattern.reset());
Stack: If you observe value of sum will increment or reset.
The objective is to hide variable accessibility from the outside world.
Disadvantage of closure
Memory leaks: Closure occupies memory and GC (Garbage collector) cannot collect memory within active closures. Hence, the chance of memory leaks is high if closure is not used well.
Debug: I found it comparatively difficult to debug closure if there is big nesting, i.e., function within function and so on....
Please share your feedback or comments.