Javascript Slice: Array slice() in JavaScript

Javascript Slice: Array slice() in JavaScript

The slice() method in JavaScript is used to extract a section of an array and return a new array containing the extracted elements. It is one of the many methods available for manipulating arrays in JavaScript.

It takes two arguments: the starting index and the ending index (exclusive) of the section to be extracted.

The syntax for the slice() method: array.slice(startIndex, endIndex);

Here, array is the array on which the slice() method is being called, startIndex is the index from where the extraction should begin (inclusive), and endIndex is the index at which the extraction should end (exclusive).

If the startIndex is not specified, the slice() method will begin extraction from the beginning of the array (i.e., index 0). If the endIndex is not specified, the slice() method will extract all elements from the startIndex to the end of the array.

The slice() method does not modify the original array. Instead, it returns a new array containing the extracted elements.

Where to use slice() method?

The slice() method is useful in a variety of situations. For example:

  1. Extracting a subarray: You can use slice() to extract a subarray from an array. This is useful when you want to work with only a portion of an array and not the entire array.
  2. Copying an array: You can use slice() to create a new array that is a copy of an existing array. This is useful when you want to create a new array that has the same elements as an existing array, but you want to modify the new array without affecting the original array.
  3. Removing elements from an array: You can use slice() to remove elements from an array. This is useful when you want to remove elements from an array without modifying the original array.
  4. Converting an array-like object to an array: You can use slice() to convert an array-like object (such as the arguments object) to an array. This is useful when you want to work with an array-like object as if it were an array.

Working Examples with slice() method in JavaScript

<script>
const code = ["Python", "JavaScript", "Java", "NodeJS", "C#"];
const newcode = code.slice(0, 3);
document.write(newcode)
</script>

As you can see we have set startIndex as 0 and endIndex as 3. So the new array has elements sliced from the 1st position from the old array to one less than the endIndex.

<script>
const code = ["Python", "JavaScript", "Java", "NodeJS", "C#"];
const newcode = code.slice(2, 3);
document.write(newcode)
</script>

Output: Java

<script>
const device = ["PC", "Laptop", "Tablet", "Console", "Mobile"];
const newdevice = code.slice(-3, -1);
document.write(newdevice)
</script>

Output: Tablet, Console

If you want to slice from startIndex till last:

<script>
const device = ["PC", "Laptop", "Tablet", "Console", "Mobile"];
const newdevice = code.slice(2);
document.write(newdevice)
</script>

Output: Tablet, Console, Mobile