0

I saw that function and tried to understand it, but I don't get what are the (a, i) arguments of that function. How they're getting a value assigned to them?

function ftRotations() {
    let str = 'abc';
    let arr = ['a', 'b', 'c'];
    return arr.map(function (a,i) {
        return str.slice(i)+str.slice(0,i)
    });
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
PRMK
  • 15
  • 4
  • Please search for the function documentation before posting: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – Brandon Hill Mar 18 '21 at 17:05

1 Answers1

0

The map method provides arguments when calling the callback, which are received by the callback in the a and i parameters it declares. (The callback doesn't use a for anything, but uses i. The callback also uses str, which it closes over because the function was created in a context where str exists.)

It may help to see a rough idea of what map does internally:

// Note: VERY ROUGH approximation, leaving out all kinds of details (like `thisArg`)
map(callback) {
    // Note: `this` is the array you called `map` on
    const result = [];
    for (let index = 0; index< this.length; ++index) {
        result[index] = callback(this[index], index, this);
        // In the callback,      ^^^^^^^^^^^  ^^^^^
        // becomes `a` −−−−−−−−−−−−−−/           \−−−−−−−becomes `i`
    }
    return result;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875