I'm studying currying functions in JS and I got stuck with this problem.
My goal is to order an array of objects by a non-arbitrary property.
let people = [
{ name: 'Bob', age: 27 },
{ name: 'Al', age: 47 }
];
var compare = function(a, b) {
if (a[property] < b[property]) return -1;
if (a[property] > b[property]) return 1;
return 0;
};
function sortBy(property) {
/* // this works
return function compare(a, b) {
if (a[property] < b[property]) return -1;
if (a[property] > b[property]) return 1;
return 0;
};
*/
// this doesn't work
return compare;
}
people.sort(sortBy('name'));
console.log(people);
With this code I get this error:
if (a[property] < b[property]) return -1;
^
ReferenceError: property is not defined
Why if I define the compare
function inside the sortBy
function I don't get any error, and instead if I define the compare
function outside I get an error?
The compare
function should not be enclosed in a closure?