Skip to main content

How to Resolve "TypeError: Cannot read properties of undefined (or null) reading 'toString'"

The TypeError: Cannot read properties of undefined (reading 'toString') and its twin ...of null (reading 'toString') are common JavaScript errors. Both occur when you try to call the .toString() method on a variable that does not hold a value that can be converted to a string, but is instead undefined or null.

This guide will explain what the .toString() 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 .toString() Method

The .toString() method is a function that exists on most JavaScript data types (like numbers, booleans, and arrays). Its purpose is to return a string representation of that value.

Correct Usage

const myNumber = 123;
const myBoolean = true;

// This works because numbers and booleans have a .toString() method.
const numString = myNumber.toString();
const boolString = myBoolean.toString();

console.log(numString); // Output: "123"
console.log(boolString); // Output: "true"

Understanding the Error: Why undefined or null?

This error happens because the .toString() method does not exist on undefined or null values. They are considered "non-values" and have no properties or methods.

The Problem Code (undefined):

let myVar; // Declared but not initialized, so it is `undefined`

// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
myVar.toString();

The Problem Code (null):

const dataFromApi = null; // A function or API might return `null`

// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'toString')
dataFromApi.toString();

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 userScore; // `userScore` is undefined

// ⛔️ Throws the error
const scoreString = userScore.toString();

Solution: Always initialize variables to a sensible default, like 0 or "".

2. An object property or array element does not exist

const user = { id: 1 }; // The 'age' property is missing

// `user.age` is undefined.
// ⛔️ Throws the error
const ageString = user.age.toString();

3. A function that was expected to return a value returned undefined instead

function getCount() {
// This function doesn't return anything.
}

const count = getCount(); // `count` is now `undefined`

// ⛔️ Throws the error
const countString = count.toString();

Solution 1: Provide a Fallback to a Default Value

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 .toString() method is called on an empty string.
const result = message.toString();
console.log(result);
// Output: ""

This is a very common and effective pattern for ensuring a variable can always be safely used.

Solution 2: Use a Conditional Check Before Calling

A more explicit and often more readable solution is to check if the variable actually has a valid value before you try to call a method on it.

A simple "truthiness" check is often sufficient, as both null and undefined are "falsy" values.

const myVar = undefined;
let result = ''; // Default value

if (myVar) {
result = myVar.toString();
} else {
console.log('Cannot convert to string, because the variable is null or undefined.');
}

console.log(`The result is: "${result}"`);
note

For a more specific check, you can use if (myVar != null), which cleverly checks for both null and undefined at the same time.

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 myVar = undefined;

// The `?.` checks if `myVar` is null or undefined. Since it is,
// the .toString() call is never made. The expression returns `undefined`.
const result = myVar?.toString();

console.log(result); // Output: undefined

You can combine this with the logical OR (||) operator to provide a default value.

const myVar = null;

// If the optional chain results in `undefined`, the `||` provides a fallback of "".
const result = myVar?.toString() || '';

console.log(result); // Output: ""

Conclusion

The TypeError: Cannot read properties of undefined (or null) reading 'toString' error is a clear signal that your variable does not hold the value you expected.

To fix it, you must add a safeguard before calling the .toString() method:

  1. Initialize your variables (Best Practice): The most robust solution is to always initialize your variables with a default value, like 0 or "".
  2. Provide a Fallback: Use the logical OR operator for a quick and safe default: const str = data || '';.
  3. Use a Conditional Check: Use if (myVar) or if (myVar != null) for clear and robust code.
  4. Use Optional Chaining (Best for Conciseness): Use const str = myVar?.toString() || ''; for a clean, modern, and safe way to perform the operation on a potentially invalid value.