Garbage Collector: A program in the browser on the JavaScript engine that kind of freezes up the unutilized memory. In the programming languages like C /C++, we generally decide how we can take memory how we have the access to the memory or how we can allocate or deallocate the memory, it’s basically up to the developers how they will use it. But in high-level languages like JavaScript, most of the work is done with JavaScript Engine, so there is Garbage Collector which takes the unused memory from the browser.
You can read Closures from here.
Relation of Garbage Collector and Closure in JavaScript: The most disadvantage of using closures in JavaScript is that there is over consumption of memory and the closed variables under the closure which are not required in the future are not garbage collected hence memory leak occurs.
Example 1: Following example covers the concept of a basic Garbage Collector.
Javascript
<script> function a() { var x = 10; return function b() { console.log(x); } } var y = a(); y(); </script> |
Output:
10
So here in the above code, function b if not present and doesn’t form closure with x then variable x would have been garbage collected. But as function b is there inside function a and forming a closure with variable x so when function b is returned variable x could not get garbage collected. But in the modern JavaScript v8 chrome engine there exists a concept of Smart Garbage Collector.
Example 2: Following example covers the concept of Smart Garbage Collector.
Javascript
<script> function a() { var x = 10, z = 92; return function b() { console.log(x); } } var y = a(); y(); console.log(z); </script> |
Output:
10 Uncaught ReferenceError: z is not defined
Here variable z and variable x both are in closure with function b but as in function b, no work is done with z so z is garbage collected while x is not garbage collected. This was the insight relation of garbage collection and closure.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#garbage_collection