In this article, you will learn about the javascript Array built-in method Array.prototype.slice()
. How does this method work in javascript?
The Array.prototype.slice()
method is used to return a new array containing the copy of the portion of an array into a new array object.
array.slice(start, end);
This method takes 2 parameters and both are optional:
default
is 0. If a negative value
is passed, then the extraction starts from the last. And If the start
is greater than the index range of the sequence, an empty array is returned. array.length
. If the end
is negative, the index position will be applied (in reverse) starting from the end of the array.The slice()
method does not change the original array
Here are some examples of the Array.prototype.slice()
method:
const languages = ["JavaScript", "Python", "C++", "Java", "Go"];
console.log(languages.slice());
// Output => ["JavaScript", "Python", "C++", "Java", "Go"]
// extract element from a array using start
console.log(languages.slice(2));
// Output => ["C++", "Java", "Go"]
// extract element from a array using start and end index
console.log(languages.slice(1, 4));
// Output => ["Python", "C++", "Java"]
// extract element from an array using negative start and negative end index
console.log(languages.slice(1, -2));
// Output => ["Python", "C++"]
// extract element from an array using negative start and negative end index
console.log(languages.slice(-3));
// Output => ["C++", "Java", "Go"]
//Using slice() on sparse arrays
console.log([1, 2, , 4, 5].slice(1, 4));
// Output => [2, empty, 4]
I hope this article will help you to understand the javascript Array built-in method Array.prototype.slice().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments