DEV Community

Cover image for Array.slice() and String.slice()
Greg C
Greg C

Posted on

Array.slice() and String.slice()

This post will explain the Array method slice() as well as the string method of the same name.

This function returns a portion or "slice" of an array or string. The return type is the same as that of the original's type.

slice() returns a new array or string, and will not change the original.

Function parameters

The slice() function can take two arguments as parameters.

Syntax

Array.slice()
Array.slice(start)
Array.slice(start, end)
Enter fullscreen mode Exit fullscreen mode

The first parameter will be the starting point for where your "slice" begins. This argument will be an index for the array or string, so its type should be a number.

let myColors = ['Red','Blue','Yellow', 'Green']
console.log(myColors.slice()) //'Red','Blue','Yellow','Green'
console.log(myColors.slice(1)) //'Blue', 'Yellow', 'Green'

let myString = "There is no spoon"
console.log(myString.slice(5)) //" is no spoon" 
console.log(myString.slice(12)) //"spoon"
Enter fullscreen mode Exit fullscreen mode

If a second argument is passed to the function, it will serve as an index to the array or string and act as the end of your "slice"

When using a second parameter, slice() will NOT include the element or character at the provided index.

let myColors = ['Red','Blue','Yellow','Green']
console.log(myColors.slice(1,3)) //'Blue','Yellow'

let myString = "There is no spoon"
console.log(myString.slice(12, 16)) //"spoo"
Enter fullscreen mode Exit fullscreen mode

You can use a negative number as your index. This will offset the starting point to the end of the array and count backwards.

let myColors = ['Red','Blue','Yellow','Green']
console.log(myColors.slice(1, -1)) //'Blue','Yellow'

let myString = "There is no spoon"
console.log(myString.slice(-11, -6)) //"is no"
Enter fullscreen mode Exit fullscreen mode

Index Range

  • If start is greater than the length of the array, the function will return an empty array/string or string.

  • If end is greater than the length of the array, the function will return everything after start

  • If start is less than end,the function will return an empty array or string.

Top comments (0)