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)
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"
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"
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"
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 afterstart
If
start
is less thanend
,the function will return an empty array or string.
Top comments (0)