The TypeError: cannot read property of ‘toLowerCase’ of undefined error occurs in JavaScript when you are trying to call the toLowerCase() method on an undefined value. This method can only be used on strings, so you must ensure that the value you are passing to it is a string and not undefined.
To fix the TypeError: cannot read property of ‘toLowerCase’ of undefined error, you need to check if the property exists before calling toLowerCase() function.
Reproduce the error
let person = {
name: "Krunal",
age: 30
};
let gender = person.gender.toLowerCase();
console.log(gender)
Output
TypeError: Cannot read properties of undefined (reading 'toLowerCase')
How to fix it?
Use the ternary operator(?) to check if the property exists before calling toLowerCase() function.
let person = {
name: "Krunal",
age: 30
};
let gender = person.gender ? person.gender.toLowerCase() : "";
console.log(gender)
Output
We get the empty string in the output because the gender property does not exist in the person object.
Using the ternary operator, we checked if it exists, and if it does not, then we set the gender property to empty, which escapes the TypeError.
Another example
let str = undefined
let res = str.toLowerCase()
console.log(res)
Output
TypeError: Cannot read property 'toLowerCase' of undefined
The above code example will throw an error because you cannot call a method (in this case, toLowerCase()) on an undefined value. You need to assign a string value to str before you can call toLowerCase().
If you try to call toLowerCase() on an undefined value, you will receive a TypeError with the message “Cannot read property ‘toLowerCase’ of undefined”.
That’s it.