Javascript - Returning a function

Introduction

Returning a function from a function is possible and useful.

The following code shows how to return a function to set which property to sort.

function createComparisonFunction(propertyName) {

    return function(object1, object2){
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if (value1 < value2){
            return -1;
        } else if (value1 > value2){
            return 1;
        } else {
            return 0;
        }
    };
}

The code above is a function inside of a function preceded by the return operator.

The propertyName argument is accessible from the inner function and is used with bracket notation to retrieve the value of the given property.

This function can be used as in the following example:

Demo

function createComparisonFunction(propertyName) {

    return function(object1, object2){
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if (value1 < value2){
            return -1;
        } else if (value1 > value2){
            return 1;
        } else {//ww  w.  j a v  a  2 s.  c  o  m
            return 0;
        }
    };
}
var data = [
    {name: "A", age: 9}, 
    {name: "B",   age: 8}];

data.sort(createComparisonFunction("name"));
console.log(data[0].name);  

data.sort(createComparisonFunction("age"));
console.log(data[0].name);

Result

In this code, an array called data is created with two objects.

Each object has a name property and an age property.

Calling createComparisonFunction creates a comparison function that sorts based on the name property.