Cannot read properties of undefined (reading 'push') in JS

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
6 min

banner

# Table of Contents

  1. Cannot read properties of undefined (reading 'push') in JS
  2. Property 'push' does not exist on type in TypeScript

# Cannot read properties of undefined (reading 'push') in JS

There are multiple reasons the "Cannot read properties of undefined (reading 'push')" error occurs:

  • Calling the push method on a variable that stores an undefined value.
  • Calling the push method at a specific index in an array.
  • Forgetting to initialize a variable to an array.
  • Calling the push method in a class, without property initialization.

cannot read property push of undefined

Most commonly, the error occurs if you try to call the push() method on a variable that stores an undefined value.

index.js
const arr = undefined; // โ›”๏ธ TypeError: Cannot read properties of undefined (reading 'push') console.log(arr.push());

typeerror cannot read property push of undefined

# Make sure to initialize the variable

A variable that has been declared but hasn't been given a value has a value of undefined in JavaScript.

index.js
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.

index.js
let arr = []; arr.push('bobby'); arr.push('hadz'); arr.push('com'); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

set variable to empty array upon declaration

The code for this article is available on GitHub

The arr variable is initialized to an empty array, which enables us to use the Array.push() method.

# Don't try to use push() after accessing the array at an index

Trying to access an array at an index that doesn't exist returns undefined.

index.js
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.

index.js
const arr = []; arr.push('a'); arr.push('b'); arr.push('c'); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'a', 'b', 'c' ]

call push method on the array itself

The code for this article is available on GitHub

# Accessing an object property that doesn't exist

Another common source of undefined values is accessing an object property that doesn't exist.

index.js
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');
We accessed the array element at index 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.

index.js
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);

set object property to empty array upon declaration

The code for this article is available on GitHub

Another way to avoid the error is to use the optional chaining (?.) operator.

index.js
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);
The ?. 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).

# Initialize the variable to an empty array

Another way to solve the error is to use the logical OR (||) operator to initialize the variable to an empty array.

index.js
const fromDb = undefined; const arr = fromDb || []; arr.push('abc'); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'abc' ]

initialize the variable to an empty array

The code for this article is available on GitHub

The logical OR (||) operator returns the value to the right if the value to the left is falsy (e.g. undefined).

# Check if the variable stores an array before calling push()

Use the Array.isArray() method to check if the variable stores an array before calling the Array.filter() method.

index.js
const arr = undefined; // โœ… using Array.isArray if (Array.isArray(arr)) { arr.push('example'); } else { console.log('arr variable does not store an array'); }

check if variable stores an array before calling push

The code for this article is available on GitHub

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.

index.js
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.

# Track down where the variable got assigned an undefined value

If 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.

A common source of 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.

# Forgetting to initialize a class property before calling push()

Make sure to initialize your class properties before calling the push() method.

index.js
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');
The code for this article is available on GitHub

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.

# Property 'push' does not exist on type in TypeScript

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.

property push does not exist on type

Here are 2 examples of how the error occurs.

index.ts
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');

# Calling the Array.push() method on a value that's not an array

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.

index.ts
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'}

# Console.log the value on which you're calling Array.push()

Otherwise, to start debugging, console.log the value you're calling the push method on and make sure it's an array.

index.ts
const obj: { name: string } = { name: '' }; console.log(Array.isArray(obj)); // ๐Ÿ‘‰๏ธ false console.log(Array.isArray([1, 2, 3])); // ๐Ÿ‘‰๏ธ true
If you determine that the value on which you're calling the push method is an array, try restarting your IDE and your development server.

# Check if the value is an array before calling Array.push()

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.

index.ts
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.

If the condition is met, TypeScript knows that the 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.

# Correct the type of the variable

If the value on which you're calling the push method is an array, you need to correct its type.

index.ts
// ๐Ÿ‘‡๏ธ 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.

# Using a type assertion to solve the error

If you have no control over the type of the variable and know that it's an array, you can use a type assertion.

index.ts
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.

We effectively tell TypeScript that the 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev