What is the purpose of the Array.slice()
method?
The Array.prototype.slice()
method allows you to create a shallow copy of a portion of an array, while preserving the original data. In other words, it extracts a subset of elements from an existing array and returns a new array with the desired data.
Syntax
Array.slice(startIndex, [endIndex]);
Example Use Cases
- Extracting a subset of elements from an array:
let originalArray = [1, 2, 3, 4, 5];
// Create a new array by slicing originalArray
// from index 1 to 3 (not inclusive)
let slicedArr = originalArray.slice(1, 3);
// Log the original and sliced array
// - Output: [1, 2, 3, 4, 5] (unchanged)
console.log(originalArray);
// - Output: [2, 3]
console.log(slicedArr);
- Creating a copy of an array:
let originalArray = [
"Apple", "Banana", "Cherry"
];
// Creates a shallow copy of the
// original array
let newArray = arr.slice();
// Adding an element to the original
// array doesn't affect the copied array
originalArray.push("Orange");
// Log the original and sliced array
// - [ 'Apple', 'Banana', 'Cherry', 'Orange' ]
console.log(originalArray);
// - [ 'Apple', 'Banana', 'Cherry' ]
console.log(newArray);
Purpose
The primary purpose of Array.prototype.slice()
is to:
- Extract specific parts: Get a subset of elements from a larger array based on a specified start and end index.
- Create a copy: Return a new array object that contains only the selected elements, without modifying the original array.
- Preserve data integrity: Ensure that the extracted elements are not affected by any subsequent modifications to the original array.
In summary, the Array.prototype.slice()
method provides a convenient way to extract specific parts of an array while preserving its integrity and creating a new copy.