TypeError: splice is not a function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

TypeError: splice is not a function in JavaScript #

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

typeerror splice is not a function

Here is an example of how the error occurs.

index.js
const arr = {}; // ⛔️ TypeError: splice is not a function arr.splice(1, 0, 'World');

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

To solve the error, console.log the value you're calling the splice method on and make sure it's an array.

index.js
const arr = ['Hello']; arr.splice(1, 0, 'World'); // 👇️ ['Hello', 'World'] console.log(arr);

If you're getting the error when working with a NodeList or other array-like object, convert the value to an array before calling the splice() method.

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

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

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

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

index.js
const arr = null; if (Array.isArray(arr)) { arr.splice(1, 0, 'example'); }
We used the Array.isArray method to check if the value is an array before calling the splice 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 splice() method.

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

We accessed the numbers property, which stores an array and called the splice() method on it.

Conclusion #

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.