Loading...
Loading...
TypeError: Cannot read properties of undefined (reading 'indexOf')This error commonly occurs when passing a regular function as a callback or when using recursive functions where the `this` context is lost. In JavaScript, `this` is determined by how a function is called, not where it is defined. If you use `this.indexOf()`, and `this` is undefined, you get this error.
Arrow functions don't have their own `this` context; they inherit it from the outer scope where they were defined.
// ❌ Loses 'this' context
function recurAtIndex(idx, node = head) {
if (this.indexOf(node.data) === idx) return node.data; // this is undefined
}
// ✅ Arrow function inherits 'this'
const recurAtIndex = (idx, node = head) => {
if (this.indexOf(node.data) === idx) return node.data;
}If an array or string might be undefined, use optional chaining before calling indexOf.
// Safely checks if array exists first
const index = myArray?.indexOf(item) ?? -1;