Cannot read properties of undefined (reading 'trim') in JS

avatar

Borislav Hadzhiev

3 min

banner

Photo from Unsplash

# Cannot read properties of undefined (reading 'trim') in JS

The "TypeError: Cannot read properties of undefined (reading 'trim')" error occurs when calling the trim() method on an undefined value.

To solve the error, initialize the value to an empty string or make sure to only call the trim method on strings.

cannot read property trim of undefined

Here is an example of how the error occurs.

index.js
const str = undefined; // โ›”๏ธ TypeError: Cannot read properties of undefined (reading 'trim') str.trim();

To solve the error, initialize the value of the variable to an empty string or make sure to only call the String.trim method on strings. Here are a couple of ways to do that.

# Use the logical OR (||) operator to provide a fallback

One way to get around the error is to use the logical OR (||) operator to provide a fallback of an empty string.

index.js
const myVar = undefined; const str = myVar || ''; // ๐Ÿ‘‰๏ธ ""

If the value to the left of the logical OR (||) operator is falsy (e.g. undefined), the operator returns the value to the right.

# Using the ternary operator

Alternatively, you can use the ternary operator, which is very similar to an if/else statement.

index.js
const str = undefined; const result1 = typeof str === 'string' ? str.trim() : ''; console.log(result1); // ๐Ÿ‘‰๏ธ ""
If the expression to the left of the question mark is truthy, the value to the left of the colon is returned, otherwise, the value to the right of the colon is returned.

# Using the optional chaining (?.) operator

You can also use the optional chaining (?.) operator to avoid the error.

index.js
const str = undefined; const result2 = str?.trim() || ''; console.log(result2); // ๐Ÿ‘‰๏ธ ""
The operator will short-circuit instead of throwing an error if the value to the left is equal to null or undefined.

# Check if the value is a string before calling trim()

Alternatively, you can use a simple if/else statement to check if the variable stores a string before calling trim().

index.js
const str = undefined; if (typeof str === '') { const result3 = str.trim(); } else { console.log('str is not a string'); }

We used the typeof operator to check if the variable stores a string before calling the String.trim() method.

# Provide a fallback value in place

You can also use the logical OR (||) operator to provide a fallback right before calling the trim() method.

index.js
const str = undefined; const result4 = (str || '').trim(); console.log(result4); // ๐Ÿ‘‰๏ธ ""

Common reasons the error occurs are:

  1. Calling the method on a class property that is not initialized to a string
  2. Calling the method on an array index that doesn't exist

# Solve the error when working with arrays

Here's an example that shows the error being thrown when using arrays.

index.js
const arr = []; // ๐Ÿ‘‡๏ธ Cannot read properties of undefined (reading 'trim') arr[0].trim();

To solve the error, make sure the element at the index is available and a string.

index.js
const arr = []; const result = typeof arr?.[0] === 'string' ? arr[0].trim() : ''; console.log(result); // ๐Ÿ‘‰๏ธ ""

Before calling the trim method, we check if the array element at the specific index is a string.

# Solve the error when working with classes

If using classes, you have to declare the class property and set it to an empty string before accessing it.

index.js
class Person { // โœ… Initialize to an empty string last = ''; // โœ… Initialize from parameters constructor(first) { this.first = first; } trimFirst() { return this.first.trim(); } trimLast() { return this.last.trim(); } } const p1 = new Person(' John '); p1.trimFirst(); p1.trimLast();

We initialized the values for the first and last class properties. Had we not done that, we would have gotten the error when trying to access the properties.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev