ottpeter
ottpeter

Reputation: 85

Array.find() gives error "TypeError: theArray.find(...) is undefined"

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.

Upvotes: 0

Views: 552

Answers (1)

ottpeter
ottpeter

Reputation: 85

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

Upvotes: 3

Related Questions