JavaScript Array slice
Method (Live Playground)
The slice
method in JavaScript is used to extract a portion of an array and returns a new array.
Here is a simple example:
let numbers = [1, 2, 3, 4, 5];
let slicedNumbers = numbers.slice(1, 3);
console.log(slicedNumbers);
// Expected output: [2, 3]
In this example, slice(1, 3)
extracts the elements starting from index 1 up to, but not including, index 3. It then returns these elements in a new array.
The slice
method does not modify the original array:
let numbers = [1, 2, 3, 4, 5];
numbers.slice(1, 3);
console.log(numbers);
// Expected output: [1, 2, 3, 4, 5]
In the example above, even after calling slice
, the numbers
array remains unchanged.
Note that if you don't specify the end index, slice
will extract elements from the start index to the end of the array:
let numbers = [1, 2, 3, 4, 5];
let slicedNumbers = numbers.slice(2);
console.log(slicedNumbers);
// Expected output: [3, 4, 5]
In this example, slice(2)
extracts all elements starting from index 2 to the end of the array.
In conclusion, the slice
method in JavaScript is a handy way to extract parts of an array without altering the original array. It's a useful tool for managing and manipulating arrays in various coding scenarios.
Practice using slice
in different contexts to fully grasp its usefulness!