Borislav Hadzhiev
Last updated: Oct 20, 2021
Check out my new book
The "pop is not a function" error occurs when the pop()
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 pop()
method on valid
arrays.
Here is an example of how the error occurs.
const obj = {name: 'Tom'}; // ⛔️ TypeError: pop is not a function obj.pop();
We called the Array.pop method on an object, which caused the error.
In this situation, we should place the object in an array, so we are able to use
the pop
method.
const arr = [{name: 'Tom'}, {name: 'Jim'}]; arr.pop(); // 👇️ [{name: 'Tom'}] console.log(arr);
If you're getting the error when working with a NodeList
or other array-like
object, you can convert the array-like object to an array, before calling the
pop()
method.
const set = new Set(['a', 'b', 'c']); const arr = Array.from(set); console.log(arr); // 👉️ ['a', 'b', 'c'] arr.pop(); console.log(arr); // 👉️ ['a', 'b']
We converted a Set
object to an array using the Array.from
method, so we can
call the pop()
method on the array.
console.log
the value you're calling the pop()
method on and make sure it's an array.Here is an example that checks if the value is an array before calling the pop
method.
const arr = null; if (Array.isArray(arr)) { arr.pop(); }
We used the Array.isArray
method to check if the value is an array before
calling the pop
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 pop()
method.
const obj = { numbers: [1, 2, 3], }; obj.numbers.pop(3); // 👇️ {numbers: [1, 2]} console.log(obj);
In the example, we accessed the numbers
property, which stores an array and
called the pop()
method on it.