Last updated: Mar 3, 2024
Reading timeยท3 min
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.
Here is an example of how the error occurs.
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.
One way to get around the error is to use the logical OR (||) operator to provide a fallback of an empty string.
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.
Alternatively, you can use the
ternary operator, which
is very similar to an if/else
statement.
const str = undefined; const result1 = typeof str === 'string' ? str.trim() : ''; console.log(result1); // ๐๏ธ ""
You can also use the optional chaining (?.) operator to avoid the error.
const str = undefined; const result2 = str?.trim() || ''; console.log(result2); // ๐๏ธ ""
null
or undefined
.trim()
Alternatively, you can use a simple if/else
statement to check if the variable
stores a string before calling trim()
.
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.
You can also use the logical OR (||) operator to provide a fallback right before
calling the trim()
method.
const str = undefined; const result4 = (str || '').trim(); console.log(result4); // ๐๏ธ ""
Common reasons the error occurs are:
Here's an example that shows the error being thrown when using arrays.
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.
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.
If using classes, you have to declare the class property and set it to an empty string before accessing it.
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.