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:
- “ReferenceError: path is not defined” in JavaScript
- “SyntaxError: Illegal return statement” in JavaScript
- “TypeError: Cannot read Property ‘0’ of Undefined” in JavaScript

Hi, my name is Joni Smith. My job is a programmer. I love learning programming languages, especially C++, C#, php, javascript, html, css. I want to share them with you. I hope my articles will bring a lot of useful knowledge to you.
Name of the university: HVNH BA
Major: htttql MIS
Programming Languages: C++, C#, php, javascript, html, css