Solve - unshift is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Check out my new book

Solve - unshift is not a function Error #

The "unshift is not a function" error occurs when the unshift() 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 unshift() method on valid arrays.

typeerror unshift is not a function

Here is an example of how the error occurs.

index.js
const arr = {num: 2}; // ⛔️ TypeError: unshift is not a function arr.unshift({num: 1});

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

In this situation, we should place the object in an array, so we are able to add new objects to the beginning of the array.

index.js
const arr = [{num: 2}]; arr.unshift({num: 1}); // 👇️ [{num: 1}, {num: 2}] 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 unshift() method.

index.js
const set = new Set(['b', 'c']); const arr = Array.from(set); console.log(arr); // 👉️ ['b', 'c'] arr.unshift('a'); console.log(arr); // 👉️ ['a', 'b', 'c']

We converted a Set object to an array using the Array.from method, so we can call the unshift() method on the array.

If the error persists, console.log the value you're calling the unshift() method on and make sure it's an array.

Here is an example that checks if the value is an array before calling the unshift method.

index.js
const arr = null; if (Array.isArray(arr)) { arr.unshift(1, 2); }

We used the Array.isArray method to check if the value is an array before calling the unshift 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 unshift() method.

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

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

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