Last updated: Mar 3, 2024
Reading timeยท6 min
There are multiple reasons the "Cannot read properties of undefined (reading 'push')" error occurs:
push
method on a variable that stores an undefined
value.push
method at a specific index in an array.push
method in a class, without property initialization.Most commonly, the error occurs if you try to call the push()
method on a
variable that stores an undefined
value.
const arr = undefined; // โ๏ธ TypeError: Cannot read properties of undefined (reading 'push') console.log(arr.push());
A variable that has been declared but hasn't been given a value has a value of
undefined
in JavaScript.
let arr; console.log(arr); // ๐๏ธ undefined // โ๏ธ TypeError: Cannot read properties of undefined (reading 'push') arr.push('abc');
We declared the arr
variable but didn't assign a value to it, so it stores an
undefined
value.
Instead, set the variable to an empty array upon declaration.
let arr = []; arr.push('bobby'); arr.push('hadz'); arr.push('com'); console.log(arr); // ๐๏ธ [ 'bobby', 'hadz', 'com' ]
The arr
variable is initialized to an empty array, which enables us to use the
Array.push() method.
push()
after accessing the array at an indexTrying to access an array at an index that doesn't exist returns undefined
.
const arr = []; // โ๏ธ TypeError: Cannot read properties of undefined (reading 'push') arr[0].push('a');
We tried to access the array at index 0
which returned undefined
because an
element at the specified index doesn't exist.
Calling the Array.push()
method on an undefined
value causes the error.
Instead, call the push()
method on the array itself.
const arr = []; arr.push('a'); arr.push('b'); arr.push('c'); console.log(arr); // ๐๏ธ [ 'a', 'b', 'c' ]
Another common source of undefined
values is accessing an object property that
doesn't exist.
const employees = [ {id: 1, name: 'Alice', tasks: []}, {id: 2, name: 'Bob'}, ]; // โ๏ธ TypeError: Cannot read properties of undefined (reading 'push') employees[1].tasks.push('buy groceries');
1
and tried to push a new value into the tasks
array, however, the tasks
array has not been initialized in the specified object.One way to get around this is to set the property to an empty array upon declaration.
const employees = [ {id: 1, name: 'Alice', tasks: []}, {id: 2, name: 'Bob', tasks: []}, ]; employees[1].tasks.push('buy groceries'); // [ // { id: 1, name: 'Alice', tasks: [] }, // { id: 2, name: 'Bob', tasks: [ 'buy groceries' ] } // ] console.log(employees);
Another way to avoid the error is to use the optional chaining (?.) operator.
const employees = [ {id: 1, name: 'Alice', tasks: []}, {id: 2, name: 'Bob'}, ]; employees[1]?.tasks?.push('buy groceries'); // [ { id: 1, name: 'Alice', tasks: [] }, { id: 2, name: 'Bob' } ] console.log(employees);
?.
operator short-circuits instead of throwing an error.The optional chaining (?.) operator
short-circuits and returns undefined
if the value to the left is nullish
(null
or undefined
).
Another way to solve the error is to use the logical OR (||) operator to initialize the variable to an empty array.
const fromDb = undefined; const arr = fromDb || []; arr.push('abc'); console.log(arr); // ๐๏ธ [ 'abc' ]
The logical OR (||) operator returns
the value to the right if the value to the left is falsy (e.g. undefined
).
push()
Use the Array.isArray()
method to check if the variable stores an array before
calling the Array.filter()
method.
const arr = undefined; // โ using Array.isArray if (Array.isArray(arr)) { arr.push('example'); } else { console.log('arr variable does not store an array'); }
The if
block is only run if the arr
variable stores an array, otherwise, the
else
block runs.
Alternatively, you can check if the variable doesn't store an array and set it to one.
let arr = undefined; if (!Array.isArray(arr)) { arr = []; arr.push('example'); } else { console.log('arr variable does not store an array'); } console.log(arr); // ๐๏ธ [ 'example' ]
If the variable doesn't store an array, we reassign it to an empty array and use
the push()
method.
undefined
valueIf the error persists, you have to track down where the variable got assigned an
undefined
value.
The push
method only exists on arrays, so trying to call it on a value of any
other type causes an error.
undefined
values is assigning the output of a function that doesn't return anything to a variable.Many built-in methods that mutate an object in place return undefined
.
All JavaScript functions that don't return a value return undefined
.
push()
Make sure to initialize your class properties before calling the push()
method.
class Person { // โ ๏ธ Initialize class property setting it to array languages = []; constructor(colors) { // โ initialize from passed in parameters this.colors = colors; } addLanguage(language) { this.languages.push(language); } addColor(color) { this.colors.push(color); } } const p1 = new Person(['blue', 'red']); p1.addLanguage('spanish'); p1.addColor('green');
We initialized the languages
property to an array inside of the class. This
helps us avoid the error when trying to use the push
method.
The same is the case for the colors
property, which we initialized inside of
the constructor.
Had we not set the languages
or colors
properties to arrays, we would have
gotten the "Cannot read properties of undefined (reading 'push')" error when
trying to use the push()
method.
The error "Property 'push' does not exist on type" occurs when we call the
push()
method on a value that isn't an array.
To solve the error, make sure to only call the push()
method on arrays or
correct the type of the variable on which you call the method.
Here are 2 examples of how the error occurs.
const obj = {}; // โ๏ธ Error: Property 'push' does not exist on type '{}'.ts(2339) obj.push('bobbyhadz.com'); // --------------------------------------------------------------- // ๐๏ธ it's an array but has an incorrect type const arr = ['one', 'two', 'three'] as unknown as { name: string }; // โ๏ธ Property 'push' does not exist on type '{ name: string; }'.ts(2339) arr.push('four');
In the first example, we called the Array.push method on an object, which caused the error.
If you want to add a property to an object, make sure the object's type permits that and use dot or bracket notation.
const obj: { name: string } = { name: '' }; // โ๏ธ Error: Property 'push' does not exist on type '{}'.ts(2339) // obj.push('hello'); obj.name = 'Bobby Hadz'; console.log(obj); // ๐๏ธ {name: 'Bobby Hadz'}
Otherwise, to start debugging, console.log
the value you're calling the push
method on and make sure it's an array.
const obj: { name: string } = { name: '' }; console.log(Array.isArray(obj)); // ๐๏ธ false console.log(Array.isArray([1, 2, 3])); // ๐๏ธ true
push
method is an array, try restarting your IDE and your development server.If the value can sometimes be an object and other times an array, you have to
use a type guard when calling the push
method.
const maybeArray = Math.random() > 0.5 ? [1, 2, 3] : { name: 'Bobby Hadz' }; if (Array.isArray(maybeArray)) { maybeArray.push(4); console.log(maybeArray); // ๐๏ธ [1, 2, 3, 4] }
The Array.isArray method serves as a type guard.
maybeArray
variable stores an array and allows us to call the push()
method.Had we tried to call the method directly on the variable, we would have gotten the "Property 'push' does not exist on type" error, because of the possibility that the variable is not an array.
If the value on which you're calling the push
method is an array, you need to
correct its type.
// ๐๏ธ it's an array but has an incorrect type const arr = ['one', 'two', 'three'] as unknown as { name: string }; // โ๏ธ Property 'push' does not exist on type '{ name: string; }'.ts(2339) arr.push('four');
The arr
variable stores an array, however, it has a different type so
TypeScript won't let us call the push()
method.
If you have no control over the type of the variable and know that it's an array, you can use a type assertion.
const arr = ['one', 'two', 'three'] as unknown as { name: string }; (arr as unknown as any[]).push('four'); console.log(arr); // ๐๏ธ ['one', 'two', 'three', 'four']
Type assertions are used when we have information about the type of a value that TypeScript can't know about.
arr
variable will be of type any[]
and not to worry about it.If this is the cause of the error in your case, it's best to figure out where the incorrect type stems from.