PacketSniffer
PacketSniffer

Reputation: 127

How is the element passed into the callback method in JavaScript?

I'm currently learning JavaScript and I am slightly confused as to how the callback function for the Array.find() method works,

I have this current code:

const numbers= [43,46,33,23,44,36,5]

function under50(num) {
    return num < 50;
}

val = numbers.find(under50);

According to the Mozilla Docs:

callback Function to execute on each value in the array, taking three arguments:

element

The current element being processed in the array.

Index

The index of the current element being processed in the array.

Array

The array find was called upon.

Now in understand the method I am passing the element, this is then being iterated over, and as soon as an element in found it will return the value. However, what confuses me, is how does it know the element when I have never explicitly passed the method the Array? If someone could post a simplistic example, it would be really helpful

Upvotes: 4

Views: 55

Answers (1)

user2437417
user2437417

Reputation:

To expand on @GerardoFurtado's comment, the value of this inside the .find() method gets set to your array. So it has both the array and the callback function. It then basically creates the equivalent of a typical for loop, and invokes your callback in that loop, passing each member.

To give a simple example, make your own .find() method.

// Be careful extending native prototypes
Array.prototype.myFind = function(callback) {
  for (var i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      return this[i]; // callback result was "truthy" so return this item
    }
  }

  return undefined; // not found, so return undefined
}

const numbers = [43,46,33,23,44,36,5]

function under50(num) {
    return num < 50;
}

const val = numbers.myFind(under50);

console.log(val);

This is quite simplified, and does not exhibit all the same behavior as the standard method, but is enough to show how to use this as a reference to the object on which the method was invoked.

For completeness, you may ask how JavaScript knows that your array has a property (a method in this case) named find. Obviously, it doesn't. But JavasCript will look for find in the prototype chain. Have a look:

const numbers= [43,46,33,23,44,36,5];
console.log("find" in numbers)

Upvotes: 5

Related Questions