JavaScript slice() method

CodingTute

JavaScript

The slice() method is a method in JavaScript that returns a new array that is a shallow copy of a portion of an existing array. It works by specifying the start and end indices of the portion of the array you want to copy, and it returns a new array that includes the elements from the start index up to but not including the end index. If the end index is omitted, the slice() method will copy all the elements from the start index to the end of the array.

Here is the syntax for the slice() method:

array.slice(start[, end])
  • start: The index at which to start copying elements from the array.
  • end: The index at which to end copying elements from the array (the element at the end index is not included in the new array). If this parameter is omitted, the slice() method will copy all the elements from the start index to the end of the array.

Here are some examples of how you can use the slice() method:

let fruits = ['apple', 'banana', 'mango', 'orange'];

// Copy the first two elements of the array
let firstTwo = fruits.slice(0, 2);  // ['apple', 'banana']
console.log(firstTwo);

// Copy all the elements of the array
let all = fruits.slice();  // ['apple', 'banana', 'mango', 'orange']
console.log(all);

// Copy the last two elements of the array
let lastTwo = fruits.slice(-2);  // ['mango', 'orange']
console.log(lastTwo);

// Copy the elements from the second to the third (inclusive)
let secondToThird = fruits.slice(1, 3);  // ['banana', 'mango']
console.log(secondToThird);

It’s important to note that the slice() method does not modify the original array. It creates a new array with the selected elements, so you can use it to create a copy of an array without modifying the original array.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

Exit mobile version