How to Resolve "TypeError: Cannot read properties of undefined (reading 'push')" Error in JavaScript
The TypeError: Cannot read properties of undefined (reading 'push') is a common JavaScript error that occurs when you try to call the .push() method on a variable that is not an array. This error message is a clear signal that the variable you are trying to add an item to is currently undefined instead of being the array you expected.
This guide will explain what the .push() method is, the common reasons your variable might be undefined, and provide the standard, robust solutions to fix this error, from proper initialization to using modern optional chaining.
Understanding the .push() Method
The .push() method is a function that exists only on arrays. Its purpose is to add one or more new elements to the end of an array.
Correct Usage:
const fruits = ['apple', 'banana'];
// This works because `fruits` is an array.
fruits.push('cherry');
console.log(fruits);
// Output: ['apple', 'banana', 'cherry']
The method modifies the original array in place and returns the new length.
Understanding the Error: Why undefined?
The error Cannot read properties of undefined (reading 'push') happens when the variable you are calling .push() on is not an array, but is instead undefined. The .push() method simply does not exist on undefined.
Example with error:
let myList; // This variable has been declared but not initialized.
console.log(myList);
// Output: undefined
// The .push() method does not exist on `undefined`.
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'push')
myList.push('new item');
Common Causes of the Error
This error typically happens for a few common reasons:
1. A variable was declared but never initialized
let userList; // `userList` is undefined
// ⛔️ Throws the error
userList.push('John Doe');
2. An object property was not initialized as an array
const user = {
id: 1,
name: 'Alice',
// The 'tasks' property is missing
};
// `user.tasks` is undefined.
// ⛔️ Throws the error
user.tasks.push('buy groceries');
3. A class property was not initialized
class Project {
// The `members` property is declared but not initialized.
members;
addMember(name) {
// `this.members` is undefined.
// ⛔️ Throws the error
this.members.push(name);
}
}
Solution 1: Always Initialize Variables to an Empty Array
The most direct and fundamental solution is to ensure your variable is an array from the moment it is created. Always initialize your variables to a sensible default, like an empty array ([]).
Solution for a simple variable
// ✅ GOOD: Initialize to an empty array.
let userList = [];
userList.push('John Doe'); // Works perfectly
Solution for an object property
const user = {
id: 1,
name: 'Alice',
tasks: [], // ✅ GOOD: Initialize the property to an empty array.
};
user.tasks.push('buy groceries'); // Works perfectly
Solution for a class property
class Project {
// ✅ GOOD: Initialize the property to an empty array.
members = [];
addMember(name) {
this.members.push(name); // Works perfectly
}
}
Solution 2: Use a Conditional Check Before Calling .push()
If a variable might be undefined (e.g., from an API response), you should check if it's a valid array before trying to use it. The Array.isArray() method is the perfect tool for this.
let userList = undefined;
if (!Array.isArray(userList)) {
// If it's not an array, create it as a new array.
userList = [];
}
// ✅ This is now safe.
userList.push('John Doe');
console.log(userList); // Output: ['John Doe']
This pattern is very robust as it handles the "repair" of the variable.
Solution 3: Use Optional Chaining (?.) for Safe Access
For modern JavaScript (ES2020 and newer), the optional chaining operator (?.) is a concise way to prevent this error, especially when dealing with nested objects. It will stop the expression if it encounters a null or undefined value.
const user = {
id: 1,
name: 'Bob',
// `tasks` property is missing
};
// The `?.` checks if `user.tasks` exists. Since it doesn't,
// the .push() method is never called, and no error is thrown.
user.tasks?.push('buy groceries');
console.log(user); // Output: { id: 1, name: 'Bob' }
Important: While this prevents the error, it does not add the item. This is a "safe failure." This is useful if adding the item is optional, but if you need to guarantee the item is added, you should combine it with a check, as in Solution 2.
Conclusion
The Cannot read properties of undefined (reading 'push') error is a clear signal that your script is trying to add an element to something that isn't an array.
To fix it, you must ensure your variable is an array before calling .push():
- Initialize your variables (Best Practice): The most robust solution is to always initialize your array variables with an empty array:
let myList = [];. - Use a Conditional Check: For variables that might not be arrays, use
if (!Array.isArray(myList)) { myList = []; }to ensure it's safe to use. - Use Optional Chaining (
?.): UsemyList?.push(...)for a clean, modern, and safe way to attempt to call the method on a potentiallyundefinedvalue, understanding that the operation will be skipped if the variable is not an array.