O'Reilly logo

Hands-On Data Structures and Algorithms with JavaScript by Kashyap Mukkamala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Closures edge case

Closures are amazing; they help us deal with a lot of problematic scenarios and also provide us with ways in which we can simulate the concept of private variables. Well, all that is good, but sometimes we tend to overlook the potential downsides that are associated with the closures. Here is what we do know and use:

function myGoodFunc() {    var a = new Array(10000000).join('*');     // something big enough to cause a spike in memory usage    function myGoodClosure() {        return a + ' added from closure';    }    myGoodClosure();}setInterval(myGoodFunc, 1000);

When we run this script in the browser and then profile it, we see as expected that the method consumes a constant amount of memory and then is GC'd and restored to the baseline ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required