Software Development and QA Tips By QASource Experts

How to Return an Array Using the Slice Method in JavaScript?

Written by Timothy Joseph | Aug 14, 2023 4:00:00 PM

The Slice() method generates a new array object containing the selected elements from an existing array. It extracts the elements beginning at the specified start position and ending at the optional end position, excluding the final element. When the second argument is omitted, the method selects elements until the end of the array.

Here are a few illustrations of the above mentioned method:

  • Example 1: const arrayIntegers = [1, 2, 3, 4, 5];

    const arrayIntegers1 = arrayIntegers.slice(0, 2); // returns [1, 2]

  • Example 2: const arrayIntegers2 = arrayIntegers.slice(2, 3); // returns [3]

  • Example 3: const arrayIntegers3 = arrayIntegers.slice(4); // returns [5]

In the first example, the slice() method selects elements from index 0 to 2 (excluding index 2), resulting in the array [1, 2].

In the second example, slice() picks the element at index 2 (excluding index 3), returning [3].

Lastly, in the third example, since the end argument is omitted, slice() selects elements from index 4 till the end of the array, producing [5].