Slice Array Method Javascript
- The
slice method is used to create a shallow copy of a portion of an array, without modifying the original array.
- Doesn't mutate the original array.
Syntax:
array.slice(start, end);
start (optional): Index to begin extraction.
- Defaults to
0 if not provided.
end (optional): Index to stop extraction (excluded from result).
- Defaults to the array's length if not provided.
Example
const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice(1, 4);
console.log(result); // Output: [2, 3, 4]
console.log(numbers); // Original arrray remains unchanged