;

Javascript Array - slice() Method


Tutorialsrack 29/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.slice().  How does this method work in javascript? 

Array.prototype.slice()

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.

Syntax
array.slice(start, end);

This method takes 2 parameters and both are optional:

  • start(Optional): This parameter holds the start position and the 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. 
  • end(optional): This parameter holds the end position and the default is 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:

Examples
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!


Related Posts



Comments

Recent Posts
Tags