Daniel.Schroeder Daniel.Schroeder - 7 months ago 11
Javascript Question

Why Am I Getting an "Undefined" Return Value from Find() Using the "This" Argument?

I'm working through "Learning JavaScript" by Ethan Brown and there is an example that is not working as it should and I'm not sure what is going wrong. The section I'm working on is dealing with searching arrays with the find() method, and the particular portion that is not doing what I expect involves using the find() method with the "this" argument.

I expect this call to find(), which returns the "daniel" Person:

arr.find(p => p.id === daniel.id);


To return the same results as this call to find(), which should also return the "daniel" Person:

arr.find(p => p.id === this.id, daniel);


Instead, the first call to find works correctly, but the second returns "undefined". Why is this?

Here is the full code example (taken from Ch. 8 of Learning JavaScript - Ethan Brown):

*NOTE THIS BOOK USES ES6

class Person {
constructor(name) {
this.name = name;
this.id = Person.nextId++;
}
}

Person.nextId = 0;

const james = new Person("Jammes"),
juliett = new Person("Juliett"),
daniel = new Person("Daniel"),
jay = new Person("Jay");

const arr = [james, juliett, daniel, jay];

// option 1: find daniel id by direct comparison
// successfully returns daniel object
arr.find(p => p.id === daniel.id);

// option 2: find jay id by using "this" arg -
// should return daniel object, instead returns undefined...
arr.find(p => p.id === this.id, daniel);

Oka Oka
Answer

Arrow functions inherit their lexical this binding from the scope in which they are created.

You can not otherwise bind, call, or apply an arrow function, which is precisely what find attempts to do when you pass in a manual thisArg binding.

Try using a regular function to note the difference.

arr.find(function (p) { return p.id === this.id; }, daniel);