TypeError: object.push is not a function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

TypeError: object.push is not a function in JavaScript #

The "object.push is not a function" error occurs because the push method is not implemented on objects. To solve the error, wrap the object in an array before calling the push method or add key-value pairs to the object using dot or bracket notation.

typeerror object push is not a function

Here is an example of how the error occurs.

index.js
const obj = { name: 'James', country: 'Chile', }; // ⛔️ TypeError: object.push is not a function obj.push({age: 30});

We called the Array.push method on an object, which caused the error.

To solve the error, we can wrap the object in an array and push a second object, or add key-value pairs to the object.

index.js
const arr = [ { id: 1, name: 'Alice', }, ]; arr.push({id: 2, name: 'Bob'}); // 👇️ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}] console.log(arr);
If the object is an element in an array, we can use the Array.push method to add other objects to the end of the array.

If you need to add key-value pairs to an object, use bracket or dot notation.

index.js
const obj = { id: 1, name: 'Alice', }; // 👇️ dot notation obj.country = 'Chile'; // 👇️ bracket notation obj['street address'] = 'Example street 123'; // 👇️ {id: 1, name: 'Alice', country: 'Chile', 'street address': ...} console.log(obj);
A general rule of thumb is to use bracket notation if the object's key contains a space, hyphen or starts with a digit, and in all other cases use dot notation as it is more concise and easier to read.

You can also conditionally check if the value is an array before calling the push method to avoid getting errors.

index.js
const arr = null; if (Array.isArray(arr)) { arr.push({id: 2, name: 'Brad'}); }

We used the Array.isArray method to check if the value is an array before calling the push method.

If have an object and you want to push values to a specific property that stores an array, access the property and call the push() method on it.

index.js
const obj = { numbers: [1, 2], }; obj.numbers.push(3); // 👇️ {numbers: [1, 2, 3]} console.log(obj);

We accessed the numbers property, which stores an array and called the push() method to add an element to the array.

Conclusion #

The "object.push is not a function" error occurs because the push method is not implemented on objects. To solve the error, wrap the object in an array before calling the push method or add key-value pairs to the object using dot or bracket notation.

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.