A Beginner’s Guide to Array.slice() in JavaScript

Khusni Ja'far
Tulisan Khusni
Published in
2 min readFeb 13, 2023

The Array.slice() method in JavaScript is used to extract a portion of an array and return it as a new array. The slice() method is an inbuilt function of JavaScript's Array object, and it allows developers to extract a portion of an array and store it in a new array.

Syntax:

array.slice(start, end)

where start is the index of the first element to extract, and end is the index of the last element to extract (the element at this index is not included in the new array). If end is omitted, all elements from start to the end of the array will be extracted.

For example:

const fruits = ['apple', 'banana', 'mango', 'orange', 'kiwi'];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // ['banana', 'mango']

In the example above, the slice() method was used to extract elements from the fruits array, starting from the index 1 (banana) and ending at index 3 (mango). The extracted portion of the array is stored in a new array slicedFruits.

It’s important to note that the slice() method does not modify the original array. Instead, it returns a new array containing the extracted elements. This makes slice() a non-destructive method, and it's a great tool to use when you want to keep the original array intact.

Another useful feature of the slice() method is that it can be used with negative indices. When using a negative index, the slice() method will extract elements counting from the end of the array. For example:

const fruits = ['apple', 'banana', 'mango', 'orange', 'kiwi'];
const slicedFruits = fruits.slice(-3, -1);
console.log(slicedFruits); // ['mango', 'orange']

In this example, the slice() method extracted the last 3 elements of the array, starting from the index -3 (mango) and ending at index -1 (orange).

In conclusion, the Array.slice() method is an essential tool for any JavaScript developer. Its ability to extract a portion of an array and return it as a new array makes it a non-destructive method that's great for keeping the original data intact. Whether you're working with arrays of numbers, strings, or objects, the slice() method is a must-have in your toolbox.

--

--