How to Resolve "TypeError: Cannot read properties of undefined (or null) reading 'toLowerCase'" Error in JavaScript
The TypeError: Cannot read properties of undefined (reading 'toLowerCase') and its twin ...of null (reading 'toLowerCase') are common JavaScript errors. Both occur when you try to call the .toLowerCase() method on a variable that is not a string, but is instead undefined or null.
This guide will explain what the .toLowerCase() method is, the common reasons your variable might be invalid, and provide the standard, robust solutions to fix this error, from providing default values to using modern optional chaining.
Understanding the .toLowerCase() Method
The .toLowerCase() method is a function that exists only on strings. Its purpose is to return a new string where all uppercase characters have been converted to lowercase. This is essential for performing case-insensitive comparisons.
Correct Usage:
const message = "Hello, World!";
// This works because `message` is a string.
const lowerMessage = message.toLowerCase();
console.log(lowerMessage); // Output: hello, world!
Understanding the Error: Why undefined or null?
This error happens when the variable you are calling .toLowerCase() on is not a string. The .toLowerCase() method simply does not exist on undefined or null values.
The Problem Code (undefined):
let myString; // Declared but not initialized, so it is `undefined`
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase')
myString.toLowerCase();
The Problem Code (null):
const dataFromApi = null; // A function or API might return `null`
// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'toLowerCase')
dataFromApi.toLowerCase();
Common Causes of the Error
This error typically occurs for a few common reasons:
1. A variable was declared but never assigned a value
let username; // `username` is undefined
// ⛔️ Throws the error
if (username.toLowerCase() === 'admin') {
// ...
}
Solution: Always initialize variables to a sensible default, like an empty string ("").
2. An object property or array element does not exist
const user = { id: 1 }; // The 'name' property is missing
// `user.name` is undefined.
// ⛔️ Throws the error
const searchName = user.name.toLowerCase();
3. A function that was expected to return a string returned something else
function getUsername() {
// This function doesn't return anything, so its result is `undefined`.
}
const username = getUsername(); // `username` is now `undefined`
// ⛔️ Throws the error
const normalizedUsername = username.toLowerCase();
Solution 1: Provide a Fallback to an Empty String
If a variable might be null or undefined, the easiest way to prevent the error is to provide a default value using the logical OR (||) operator.
const dataFromApi = undefined;
// If `dataFromApi` is falsy (like undefined or null), use an empty string instead.
const message = dataFromApi || '';
// ✅ This is now safe. The .toLowerCase() method is called on an empty string.
const result = message.toLowerCase();
console.log(result); // Output: ""
This is a very common and effective pattern for ensuring a variable is always a string.
Solution 2: Use a Conditional Check Before Calling
A more explicit and often more readable solution is to check if the variable is actually a string before you try to call a string method on it. The typeof operator is the perfect tool for this.
const message = undefined;
if (typeof message === 'string') {
const result = message.toLowerCase();
console.log(result);
} else {
console.log('Cannot convert to lowercase, because `message` is not a string.');
}
This approach makes your code very robust and its intent clear.
Solution 3: Use Optional Chaining (?.) for Safe Access
For modern JavaScript (ES2020 and newer), the optional chaining operator (?.) is the most concise and elegant solution. It allows you to safely attempt to call a method. If the value on the left is null or undefined, the expression "short-circuits" and returns undefined instead of throwing an error.
const message = undefined;
// The `?.` checks if `message` is null or undefined. Since it is,
// the .toLowerCase() call is never made. The expression returns `undefined`.
const result = message?.toLowerCase();
console.log(result); // Output: undefined
You can combine this with the logical OR (||) operator to provide a default value.
const message = null;
// If the optional chain results in `undefined`, the `||` provides a fallback of "".
const result = message?.toLowerCase() || '';
console.log(result); // Output: ""
Conclusion
The TypeError: Cannot read properties of undefined (or null) reading 'toLowerCase' error is a clear signal that your variable is not the string you expected it to be.
To fix it, you must add a safeguard before calling the .toLowerCase() method:
- Initialize your variables (Best Practice): The most robust solution is to always initialize your string variables with a default value, like an empty string:
let message = "";. - Provide a Fallback: Use the logical OR operator for a quick and safe default:
const message = data || '';. - Use a Conditional Check: Use
if (typeof message === 'string')for clear and robust code. - Use Optional Chaining (Best for Conciseness): Use
const result = message?.toLowerCase() || '';for a clean, modern, and safe way to perform the operation on a potentially invalid value.