Better approach nulling variables, objects in Javascript

2.5k Views Asked by At

I am building something for mobile and would like somehow to clear, null objects, variables to release a bit of memory. Here I have two quick examples, both are anonymous functions as I believe but what way is better or more valid approach? Sorry if I get it all wrong. To me both seem to do the same thing although I like more the first one as objects wont be created until I need it. The second version would immediately execute the code for creating variables, objects etc. but not doing the main build function until I need it.

I am just trying to figure out what way is more common. I know that beginners like me mostly misunderstand the use of anonymous functions.

V1

var app = function() {

        //create variables, objects
        var a = 'Data 1';
        var b = 'Data 2';

        //do some things    
        console.log(a + ', ' + b);

        //do a cleanup
        app.cleanup = function() {

            a = null;
            b = null;
            console.log(a, b);

        }
    }
    setTimeout(app, 200);

V2

var app = {};

    (function(){

        //create variables, objects
        var a = 'Data 1';
        var b = 'Data 2';

        app.build = function(){                 

            //do some things
            console.log(a + ', ' + b);          

        }

        //do a cleanup
        app.cleanup = function(){

            a = null;
            b = null;
            console.log(a, b);

        }   

        setTimeout(app.build,200);

    })();

Later in html or event

<input type="button" onclick="app.cleanup()" value="clean" />
1

There are 1 best solutions below

0
On BEST ANSWER

You shouldn't be worrying about freeing up resources. JavaScript has a garbage collector which will pick up variables which fall out of scope and destroy them. Delete a reference to an object when you don't need it using delete obj.yourReference, reference = null or something similar, and let the garbage collector do the rest.

You'll find that #1 will automatically reclaim the a and b variables itself automatically, if you remove your app.cleanup() definition. Unless you do that, a and b are both enclosed in the closure created by the cleanup function you're leaving behind, so you're stopping the garbage collector from doing it's thing.

To get rid of the whole app in #1, you'll have to do delete window.app or app = null as window holds a reference to it.