Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Jisu Han
The "slice is not a function" error occurs when the slice()
method is called
on a value that is not of type string or array. To solve the error, convert the
value to a string or array before calling the method or make sure to only call
the slice
method on strings or arrays.
Here is an example of how the error occurs.
const str = 9876; // ⛔️ TypError: slice is not a function const result = str.slice(2);
We called the slice
method on a number and got the error. The slice
method
is implemented on 2 data types in JavaScript -
String.slice
and
Array.slice.
To solve the error, either convert the value to a string or array before calling the method or only call the method if the value is of the correct type.
// 👇️ For Strings const num = 9876; const result1 = num.toString().slice(2); console.log(result1); // 👉️ "76" // 👇️ For Arrays const set = new Set(['a', 'b', 'c']); const result2 = Array.from(set).slice(2); console.log(result2); // 👉️ ['c']
In the first example, we convert the number to a string using the toString()
method before calling the slice
method.
In the second example, we used the Array.from
method to convert a Set
to an
array before calling the slice
method.
slice
method.const num = 9876; const result1 = typeof num === 'string' ? num.slice(2) : ''; console.log(result1); // 👉️ "" // 👇️ For Arrays const set = new Set(['a', 'b', 'c']); const result2 = Array.isArray(set) ? set.slice(2) : []; console.log(result2); // 👉️ []
In both examples, we used the ternary operator, which is very similar to an
if/else
statement.
In the first example, we check if the value has a type of string
. If it does,
we return the result of calling the slice
method on it, otherwise return an
empty string.
In the second example, we check if the value is an array using the
Array.isArray
method.
If the value is an array, we return the result of calling the slice
method on
it, otherwise return an empty array.
console.log
the value you're calling theslice
method on and make sure it's either of type string or array.If you have an object, there is a very good chance you have to access a specific property on the object that has a value of an array or string.