Solve - Cannot read Property 'toLowerCase' of Null in JS

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Jace & Afsoon

Solve - Cannot read Property 'toLowerCase' of Null #

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.

index.js
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.

index.js
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.

The last example initializes the value for the 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee