slice() Methods in JavaScript

JavaScript
slice() Methods in JavaScript
javascriptslice methodarray methods

slice() is a built-in method in JavaScript that is used to extract a portion of an array.

slice() Methods in JavaScript

  • is a built-in method in JavaScript that is used to extract a portion of an array.
  • It returns a new array containing the selected elements, without changing the original array.
  • The method takes two arguments: the starting index and the ending index. The ending index is not included in the resulting array.

Example:

  • Let's take an array with elements like "shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack".
1let products = ["shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack"];

To get the first 5 products on the page, use the method with start index and end index :

1let products = ["shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack"];
2
3let itemInPage = products.slice(0, 5);
4
5itemInPage.forEach(item => {
6    document.write(item + "<br>");
7});
8
9
10
11// Output:
12shirt
13jeans
14shoes
15laptop
16watch

The array now contains the first 5 products: "shirt", "jeans", "shoes", "laptop", "watch".

  • To get the last 5 products on the page, use the method with a negative index :
1let products = ["shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack"];
2
3let itemInPage = products.slice(-5);
4
5itemInPage.forEach(item => {
6    document.write(item + "<br>");
7});
8
9
10
11// Output:
12phone
13book
14camera
15headphones
16backpack

The array now contains the last 5 products: "phone", "book", "camera", "headphones", "backpack".

  • The method allows us to extract parts of an array without modifying the original array.