1

Why is the object undefined, if I call it in arr.find with 'this'?

let o = { name: 'foobar' };
let arr = [3, o, 4, 5];

arr.find(x => console.log(this), o);
4
  • 2
    The lambda is capturing this from the current scope, and so your code logs window four times. It works as expected if you convert the lambda to a regular anonymous function. Your callback doesn't return a truthy value though, so it won't ever find anything. Commented Nov 20, 2018 at 21:01
  • What do you expect this to refer to? From what you posted it's not clear why exactly it's undefined, but it would not be weird for it to be undefined. Commented Nov 20, 2018 at 21:01
  • 1
    arr.find receives a condition and returns the first element that satisfies the condition. What you're doing is "out of the given array, return the first element that - console.log". console.log returns undefined, so the condition returns undefined for all elements and eventually finds nothing. Commented Nov 20, 2018 at 21:03
  • Thanks for the explanation @Amy. Im new to JS and did not think of this mechanims. Commented Nov 20, 2018 at 21:16

1 Answer 1

4

If you want to use the second parameter of find() to set this you need to pass a regular function because you can't re-bind this to arrow functions:

let o = { name: 'foobar' };
let arr = [3, o, 4, 5];

let p = arr.find(function(x){
         console.log(this)
         return x === this
 }, o);

 console.log("found:", p)

Sign up to request clarification or add additional context in comments.

1 Comment

What I'm saying @geoge is that you can't do call bind(someObj) on an arrow function to set the value of this find()'s second param is a value to rebind the function to. Maybe I phrased it poorly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.