Array Methods - Slice
Let's learn how to use slice
to extract specific parts of an array.
Arrays Start at Index 0
In most programming languages, array indices (the numbers representing the position of elements in an array) start at 0.
This is a traditional convention in programming.
const fruits = ['Apple', 'Banana', 'Cherry', 'Grape', 'Orange'];
You can access each element of the fruits
array as follows:
-
First element:
fruits[0]
=> "Apple" -
Second element:
fruits[1]
=> "Banana" -
Fifth element:
fruits[4]
=> "Orange"
Slicing an Array
You can use the slice()
method to extract a portion of an array. slice()
returns a new array and does not modify the original array.
Basic structure:
array.slice([start index], [end index])
-
Start index: The position in the array where extraction begins. If omitted, slice starts from the beginning of the array.
-
End index: The position in the array where extraction ends, but it does not include this index itself. If omitted, slice extracts through the end of the array.
Example:
const fruits = ['Apple', 'Banana', 'Cherry', 'Grape']; const selected = fruits.slice(1, 3); console.log(selected); // ["Banana", "Cherry"]
The cut
method is used to slice an array.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result