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

avatar

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.

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);

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.

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

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee