0

I'm getting TypeError: theArray.find(...) is undefined from a code that is in essence similar to this:

if (!Array.isArray(theArray)) console.error("WARNING! theArray is not an array: ", theArray);
console.log(theArray.find((element) => element).someProperty);

I'm not getting the error message WARNING! theArray is not an array, but I'm getting the error theArray.find(...) is undefined

The error message does not say that theArray is undefined, this is an error message that I would except when theArray is not of type array.

Inside the array function there would be a more complex logic, but I simlified it to focus on the Array.find() problem. The variable theArray is an array of complex objects, with a lot of properties.

3
  • 1
    How do I ask a good question? -> Add a minimal reproducible example Commented Oct 20, 2021 at 10:33
  • Two times voted to close because of debugging details - without comment. What needs to be debugged? Commented Oct 20, 2021 at 10:58
  • most likely the problem is related to someProperty. I still haven't solved my own problem, but it seems that without someProperty it would work, so this will be a problem with properties and not Array.find(). I will write down the solution when I find it. Commented Oct 20, 2021 at 11:03

1 Answer 1

3

Array.find will return undefined when it does not find a result.

The error message means that find() function returned undefined, then someProperty can not be found on undefined.

Example for clarification:

let testArray = [{a: 3}, {a: 4}, {a: 5}];
let notArray = 5;

testArray.find((item) => item.a === 3); will result Object { a: 3 }
tetArray.find((item) => item.a === 3); will result Uncaught ReferenceError: tetArray is not defined
notArray.find((item) => item.a === 3); will result Uncaught TypeError: notArray.find is not a function
testArray.find((item) => item.a === 7).a; will result Uncaught TypeError: testArray.find(...) is undefined

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

2 Comments

That's why you're supposed to add a minimal reproducible example that shows the behavior you're asking about... Or start debugging before you ask on SO.
The real object is very complex, and also, I was overly confident in that .find() will always find a result in my situation.

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.