Skip to main content
Practice

Array Method - Slice

Let's learn how to extract a specific portion of an array using the slice method.


Arrays Start at Index 0

In most programming languages, the index of an array (the number representing the position of elements within the array) starts 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:

The slice() method can be used to extract a portion of an array. slice() does not modify the original array but returns a new array.

Basic structure:

array.slice([start index], [end index])
  • Start index: The position in the array to start extracting; if omitted, extraction starts from the beginning of the array.

  • End index: The position in the array to stop extraction, but does not include this position itself; if omitted, extraction continues to the end of the array.


Example:

const fruits = ['Apple', 'Banana', 'Cherry', 'Grape'];
const selected = fruits.slice(1, 3);

console.log(selected); // ["Banana", "Cherry"]

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.