How to Use the slice() Method
The basic idea of the slice()method is as follows:
slice(start, end)
Parameter 1: start
is a zero-based index at which to start extraction. If start
is undefined, slice
starts from the index 0.
Parameter 2: end
is a zero-based index before which to end extraction. slice
extracts up to but not including end
.
!! IMPORTANT !!
The slice() method will not modify the original array. It will return a shallow copy of a portion of an array into a new array object.
Case 1: No Parameters
const numbers = [0, 1, 2, 3, 4];
const copiedNumbers = numbers.slice();
console.log(numbers); // [0, 1, 2, 3, 4]
console.log(copiedNumbers); // [0, 1, 2, 3, 4]
Case 2: Only Setting start
const numbers = [0, 1, 2, 3, 4];
const copiedNumbers = numbers.slice(2);
console.log(numbers); // [0, 1, 2, 3, 4]
console.log(copiedNumbers); // [2, 3, 4]
const numbers = [0, 1, 2, 3, 4];
const copiedNumbers = numbers.slice(-3);
console.log(numbers); // [0, 1, 2, 3, 4]
console.log(copiedNumbers); // [2, 3, 4]
Case 3: Setting start
and end
const numbers = [0, 1, 2, 3, 4];
const copiedNumbers = numbers.slice(2, 4);
console.log(numbers); // [0, 1, 2, 3, 4]
console.log(copiedNumbers); // [2, 3]
const numbers = [0, 1, 2, 3, 4];
const copiedNumbers = numbers.slice(-3, -1);
console.log(numbers); // [0, 1, 2, 3, 4]
console.log(copiedNumbers); // [2, 3]