Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Jace & Afsoon
The "Cannot read Property 'toLowerCase' of null" error occurs when the
toLowerCase()
method is called on a variable that stores a null
value. To
solve the error, make sure to only call the toLowerCase
method on strings.
Here is an example of how the error occurs.
const str = null; // ⛔️ Cannot read properties of null (reading 'toLowerCase') str.toLowerCase();
To solve the "Cannot read Property 'toLowerCase' of null" error, initialize
the value on which you're calling the method to an empty string or make sure to
only call the toLowerCase()
method on strings.
const example = null; // ✅ initialize to string if falsy const str = example || ''; // ✅ Using optional chaining const result1 = str?.toLowerCase() || ''; console.log(result1); // 👉️ "" // ✅ Using ternary const result2 = typeof str === 'string' ? str.toLowerCase() : ''; console.log(result2); // 👉️ "" // ✅ using if/else if (typeof str === 'string') { const result3 = str.toLowerCase(); } else { console.log('str is not a string'); } const result4 = (str || '').toLowerCase(); console.log(result4); // 👉️ ""
We used the logical OR (||) operator to provide a fallback if the value of the
example
variable is falsy (e.g. null
).
The second example uses the
optional chaining (?.)
operator, which short-circuits returning undefined if the value to the left is
null
or undefined
.
The third example uses a
ternary operator,
which is very similar to an if/else
statement.
The fourth example uses a basic if/else
to make sure we only call the
String.toLowerCase
method on strings.
str
variable right before calling the toLowerCase()
method.If the value of the str
variable is falsy (e.g. null
), it would be set to an
empty string, so we can avoid getting the error.