JavaScript Closure Use Case - Avoid memory leaks and improve performance
The closure is a very important concept of JavaScript both in terms of performance improvement of your application and Interviews. All JavaScript developers have to learn this concept. With this blog, we can understand how we can avoid excess memory leaks using a closure. A memory leak is one of the major problems in JavaScript. JavaScript doesn't have memory management primitives, unlike c which has malloc, calloc for creating and freeing memory. In javaScript, garbage collection happened automatically. So here we need to be extra cautious to handle memory leaks.
Here is an example of how closure can be a life savior for a JavaScript developer
Before closure:
function multiplier(b){
let a = Math.pow(5,5)
return a * b
}|
multiplier (20) // 62500
multiplier (40) // 125000
Here, whenever multiplier called let Val = Math.Pow(5,5) is created and preserves certain memory, for this particular case, large memory is used due to the large numeric value is generating here.
After Closure -
function multiplier(){
let a = Math.pow(5,5)
return function(b){
return a * b
}
}
let multiplicand = multiplier()
multiplicand(20) // 62500
multiplicand(40) // 125000
With this example, the inner function creates a closure with variables defined in its lexical scope and they would be available outside too. So here, let value = Math.pow(5,5) is not created again and again which saves excessive memory leaks.
This approach also improves application performance.
#happylearning #javaScriptworld