Alexey Tseitlin
Alexey Tseitlin

Reputation: 1309

Arrow function. To what variables the function refers to?

I am stuck on an example from a JS book. Here is an Arrow function. Works fine, but what variables the function refers to? How does it know what to do with "a, b"?

I don't understand what is going behind the scenes...

const arr = [{
  name: "Suzanne"
}, {
  name: "Jim"
}, {
  name: "Trevor"
}, {
  name: "Amanda"
}];

// arr sorted reverse alphabetically 
// by second letter of name property

console.log(arr.sort((a, b) => a.name[1] < b.name[1]));

Upvotes: 1

Views: 75

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

The values of a and b are determined by the Array#sort function, which is what calls your arrow function. It's the same as with normal functions; for instance, your code would work identically like this:1

console.log(arr.sort(function(a, b) {
    return a.name[1] < b.name[1];
});

Inside Array#sort, you can imagine a call to your callback:

function Array_sort(callback) {
    // ...

    while (not_done_sorting_yet) {
        // ...
        result = callback(element[x], element[y]); // The call to your callback
        // ...code using result...
    }

    // ...
}

Just as with any callback (indeed, any function), it's the code calling it that determines what arguments it gets and their values. (Ignoring partial application for simplicity.)


1 BTW: That code is wrong, the return value from the sort callback is supposed to be a number, not a boolean: 0 if a and b are equal for sorting purposes, less than zero is a is "less than" b for sorting purposes (should come before b), and greater than zero if a is "greater than" b for sorting purposes (should come after b).

Here's the correct version (for an array "sorted reverse alphabetically by second letter of name property" [from the comment in the quoted code]):

// Reverse alpha by second letter in name
console.log(arr.sort((a, b) => b.name[1].localeCompare(a.name[1])));

...since String#localeCompare returns an appropriate value for whether the string you call it on is "less than" or "greater than" the one you call it with. (And name[1] is a one-character string.)

Upvotes: 4

Related Questions