Last Updated: February 25, 2016
·
373
· madisonw

Closures for pre-proccessing

One of the many uses for closures in Javascript is preprocessing your data and functions so you only have to load them once! Take this function for example:

var process_employee_data = function() {
    function get_employee_name(employee) {
        return employee.first_name + " " + employee.last_name;
    }

    var employee_data = $.getJSON("api/url.php");

    //code that processes employee_data using the helper function get_employee_name
}

So with this function, every time you want to process employee data, you are not only grabbing the data with every call, but you are also re-declaring the getemployeename() function upon every run of this function.

To improve the performance of this function, you can preprocess the data that should remain constant upon every invocation of the function! It would end up looking something like this:

var process_employee_data = (function(){
     function get_employee_name(employee) {
        return employee.first_name + " " + employee.last_name;
    }

    var employee_data = $.getJSON("api/url.php");
    return function() {
        //code that processes the data using the preprocessed function declared
    }
}())

Now the declaration of utility functions and the gathering of data is only done once during the entire execution of your program on this page refresh.