How to Resolve "TypeError: Cannot read properties of undefined (reading 'slice')" Error in JavaScript
The TypeError: Cannot read properties of undefined (reading 'slice') is a common JavaScript error that occurs when you try to call the .slice() method on a variable that is not an array or a string, but is instead undefined. This error is a clear signal that the variable you're trying to work with doesn't hold the value you expect.
This guide will explain what the .slice() method is, the common reasons your variable might be undefined, and provide the standard, robust solutions to fix this error, from providing default values to using modern optional chaining.
Understanding the .slice() Method
The .slice() method is a function that exists on arrays and strings. It is used to extract a portion of the array or string and returns a new array or string, without modifying the original.
Correct Usage for Array:
const fruits = ['apple', 'banana', 'cherry', 'date'];
const firstTwo = fruits.slice(0, 2);
console.log(firstTwo); // Output: ['apple', 'banana']
Correct Usage for String:
const message = "Hello, world!";
const firstFive = message.slice(0, 5);
console.log(firstFive); // Output: Hello
Understanding the Error: Why undefined?
The error Cannot read properties of undefined (reading 'slice') happens when the variable you are calling .slice() on is not an array or a string, but is instead undefined. The .slice() method simply does not exist on undefined.
Example of error:
let myVar; // This variable has been declared but not initialized.
console.log(myVar);
// Output: undefined
// The .slice() method does not exist on `undefined`.
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'slice')
myVar.slice(0);
Common Causes of the Error
This error typically happens for a few common reasons:
1. A variable was declared but never assigned a value
let userList; // `userList` is undefined
// ⛔️ Throws the error
const firstFiveUsers = userList.slice(0, 5);
Solution: Always initialize variables to a sensible default, like [] for an array or "" for a string.
2. An object property or array element does not exist
const user = { id: 1 }; // The 'name' property is missing
// `user.name` is undefined.
// ⛔️ Throws the error
const firstName = user.name.slice(0, 4);
3. A function that was expected to return an array or string returned undefined instead
function getItems() {
// This function doesn't return anything, so its result is `undefined`.
}
const items = getItems(); // `items` is now `undefined`
// ⛔️ Throws the error
const firstItem = items.slice(0, 1);
Solution 1: Provide a Fallback to a Default Value
If a variable might be undefined (e.g., from an API call), the easiest way to prevent the error is to provide a default value using the logical OR (||) operator.
Solution for an Array
const dataFromApi = undefined;
// If `dataFromApi` is falsy (like undefined), use an empty array instead.
const items = dataFromApi || [];
// ✅ This is now safe. The .slice() method is called on an empty array.
const firstThree = items.slice(0, 3);
console.log(firstThree); // Output: []
Solution for a String
const message = undefined;
const firstWord = (message || '').slice(0, 5);
console.log(firstWord); // Output: ""
Solution 2: Use a Conditional Check Before Calling
A more explicit and often more readable solution is to check if the variable is a valid type before you try to call a method on it.
Solution for Arrays
Use the Array.isArray() method.
const items = undefined;
if (Array.isArray(items)) {
const firstThree = items.slice(0, 3);
console.log(firstThree);
} else {
console.log('Cannot slice, because `items` is not an array.');
}
Solution for Strings
Use the typeof operator.
const message = undefined;
if (typeof message === 'string') {
const firstWord = message.slice(0, 5);
console.log(firstWord);
} else {
console.log('Cannot slice, because `message` is not a string.');
}
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 items = undefined;
// The `?.` checks if `items` is null or undefined. Since it is,
// the .slice() call is never made. The expression returns `undefined`.
const firstThree = items?.slice(0, 3);
console.log(firstThree); // Output: undefined
You can combine this with the logical OR (||) operator to provide a default value.
const items = undefined;
// If the optional chain results in `undefined`, the `||` provides a fallback of [].
const firstThree = items?.slice(0, 3) || [];
console.log(firstThree); // Output: []
Conclusion
The Cannot read properties of undefined (reading 'slice') error is a clear signal that your variable is not the array or string you expected it to be.
To fix it, you must add a safeguard before calling the .slice() method:
- Initialize your variables (Best Practice): The most robust solution is to always initialize your variables with a default value, like
[]or"". - Provide a Fallback: Use the logical OR operator for a quick and safe default:
const items = data || [];. - Use a Conditional Check: Use
if (Array.isArray(items))orif (typeof message === 'string')for clear and robust code. - Use Optional Chaining (Best for Conciseness): Use
const result = items?.slice(...) || [];for a clean, modern, and safe way to perform the operation on a potentiallyundefinedvalue.