TypeError: cannot read property of ‘toLowerCase’ of undefined error occurs when you try 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.
Here are two ways to fix it:
- Using ternary operator
- Using optional chaining
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 TypeError?
Solution 1: Using ternary operator
Use the ternary operator(?) to check the property’s existence before calling the 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.
Solution 2: Using optional chaining (?.)
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().
To call toLowerCase() on an undefined value, you will receive a TypeError.
Let’s fix this error using the optional chaining (?.) operator.
let str = undefined
let res = str?.toLowerCase() || '';
console.log(res)
Output is an empty string, and the error is fixed!