To fix the TypeError: cannot read property of ‘toLowerCase’ of undefined error, you need to “check if the property exists before calling the toLowerCase() function using the ternary operator.”
TypeError: cannot read property of ‘toLowerCase’ of undefined error occurs in JavaScript 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.
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?
Here are two ways to fix the TypeError: Cannot read property ‘toLowerCase’ of undefined error.
- Using the ternary operator
- Using optional chaining
Solution 1: Using the ternary operator
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.
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 with the message “Cannot read property ‘toLowerCase’ of undefined”.
let str = undefined
let res = str?.toLowerCase() || '';
console.log(res)
Output is an empty string.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.