How does this Array.prototype.find() work?

What I do not understand is the function and its parameter fruit, because it's not being passed anything.

var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
  return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries));

Solution 1:

...because it's not being passed anything.

It is being passed something, you just don't see the code doing it, which is inside the Array.prototype.find method's code. Remember, this line:

console.log(inventory.find(findCherries));

...passes the value of findCherries (a function reference) into find, it doesn't call findCherries. find does that, once for each entry in the array, supplying three arguments (only one of which findCherries uses). The first of those arguments is the array entry for that call.

The full polyfill for Array.prototype.find makes for tricky reading, so let's do something similar but simpler so you can see the calls:

// A bit like Array.prototype.find, but **not** the same; much simplified
function fakeFind(callback) {
  for (var index = 0; index < this.length; ++index) {
    var entry = this[index];
    //  vvvvvvvvvvvvvvvvvvvvvvvvvvvv---- This is where findCherries is called
    if (callback(entry, index, this)) {
      return entry;
    }
  }
  return undefined;
}

Live copy:

// A bit like Array.prototype.find, but **not** the same; much simplified
function fakeFind(callback) {
  for (var index = 0; index < this.length; ++index) {
    var entry = this[index];
    //  vvvvvvvvvvvvvvvvvvvvvvvvvvvv---- This is where findCherries is called
    if (callback(entry, index, this)) {
      return entry;
    }
  }
  return undefined;
}
Object.defineProperty(Array.prototype, "fakeFind", {
  value: fakeFind
});
var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
  return fruit.name === 'cherries';
}

console.log(inventory.fakeFind(findCherries));