How to Fix TypeError: Cannot read property ‘toLowerCase’ of undefined

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.

  1. Using the ternary operator
  2. 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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.