How to solve “TypeError: slice is not a function” in JavaScript

“TypeError: slice is not a function” in JavaScript

This article will share with you how to solve the error “TypeError: slice is not a function” in JavaScript. Let’s go into some methods below.

Why does the error “TypeError: slice is not a function” in JavaScript happen?

Example code

let myNumber= 8234726;
myNumber.slice(3);

Output

TypeError: myNumber.slice is not a function

In the example above, myNumber.slice() is called a number type, leading to an error. This error occurs because you use the slice() method on a value that is not a string or array of type. There are some useful ways below to help you deal with this error.

Some ways to fix the error “TypeError: slice is not a function” in JavaScript

Convert to String

The slice() method only works on strings or arrays. To convert a number to a string we use toString() function. 

Code sample

let myNumber = 8234726;

// convert a number to a string
let myString = myNumber.toString();

// slice the string with a start index is 2 and an end index is 4
console.log(myString.slice(2,4));

Output

34

Convert to Array by Array.from()

Array.from() allows us to convert the following two types of values into arrays:

  • Array-like values
  • Iterable values like Set, Map

Code sample

let myNumber = 8234726;
let mySet = new Set([1, 3, 2, 5, 9]);
 
// convert a number to string type then convert string type to an array
let myArr1 = Array.from(String(myNumber));

// convert a set to an array
let myArr2 = Array.from(mySet);
 
// slice the array
console.log(myArr1.slice(2,6));
console.log(myArr2.slice(1,4));

Output

(4) ['3', '4', '7', '2']
(3) [3, 2, 5]

Convert to Array by spread operator …

In addition, we can take the spread operator to convert the value to an array type as follows.

Code sample

let myNumber = 8234726;
let mySet = new Set([1, 3, 2, 5, 9]);
 
// convert a number to string type, then convert string type to an array
let myArr1 = [...String(myNumber)];

// convert a set to an array
let myArr2 = [...mySet];
 
// slice the array
console.log(myArr1.slice(3, 6));
console.log(myArr2.slice(1));

Output

(3) ['4', '7', '2']
(4) [3, 2, 5, 9]

Summary

Above, I have shown you how to solve the error “TypeError: slice is not a function” in JavaScript using the toString(), Array.from() and spread operator method. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about how to fix errors in Javascript here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *