Solve - object.push is not a function Error in JavaScript


Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - object.push is not a function Error #

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.

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.

const arr = [ { id: 1, name: 'Alice', }, ]; arr.push({id: 2, name: 'Bob'}); // 👇️ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}] console.log(arr);

By wrapping the object in an array, we are able to use the Array.push method to add objects to the end of the array.

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

const obj = { id: 1, name: 'Alice', }; // 👇️ dot notation = '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 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.

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 you're working with an object and you want to push values to a specific property that stores an array, you can do that by accessing the property and calling the push() method on it.

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

In the example, we access the numbers property, which stores an array and called the push() method.

Use the search field on my Home Page to filter through my more than 1,000 articles.