slice() Methods in JavaScript

JavaScript1 min read
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

  • slice() 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 slice() 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 products with elements like "shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack".
let products = ["shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack"];

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

let products = ["shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack"]; let itemInPage = products.slice(0, 5); itemInPage.forEach(item => { document.write(item + "<br>"); }); // Output: shirt jeans shoes laptop watch

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

  • To get the last 5 products on the page, use the slice() method with a negative index -5:
let products = ["shirt", "jeans", "shoes", "laptop", "watch", "phone", "book", "camera", "headphones", "backpack"]; let itemInPage = products.slice(-5); itemInPage.forEach(item => { document.write(item + "<br>"); }); // Output: phone book camera headphones backpack

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

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