Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
The "push is not a function" error occurs when the push()
method is called
on a value that is not an array. To solve the error, convert the value to an
array before calling the method, or make sure to only call the push()
method
on valid arrays.
Here is an example of how the error occurs.
const arr = {name: 'Tom'}; // ⛔️ Uncaught TypeError: arr.push is not a function arr.push({name: 'James'});
We called the Array.push method on an object, which caused the error.
In this situation, we should place the object in an array, so we are able to push new objects into the array.
const arr = [{name: 'Tom'}]; arr.push({name: 'James'}); // 👇️ [{name: 'Tom'}, {name: 'James'}] console.log(arr);
If you got the error when working with a NodeList
or other array-like object,
convert the array-like object to an array before calling the push()
method.
const set = new Set(['a', 'b']); const arr = Array.from(set); console.log(arr); // 👉️ ['a', 'b'] arr.push('c'); console.log(arr); // 👉️ ['a', 'b', 'c']
We used the Array.from()
method to convert a Set
object to an array, so we
can call the push()
method on the array.
console.log
the value you're calling the push()
method on and make sure it's an array.Here is an example that checks if the value is an array before calling the
push()
method.
const arr = null; if (Array.isArray(arr)) { arr.push('example'); }
Array.isArray
method to check if the value is an array before calling the push
method.If you're working with an object, there's a good chance that you need to access
a specific property that stores an array, so you can call the push()
method.
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 on the array.