The slice method in JavaScript is utilized to retrieve a segment of an array and return that segment as a new array. It is important to note that this method does not alter the original array in any way.
Syntax
The syntax for the slice method is illustrated as follows:
array.slice(start, end)
Parameter
The start parameter is not mandatory. It denotes the index at which the method begins to retrieve the elements.
end - This parameter is not mandatory. It indicates the index at which the method ceases to extract elements.
The slice function generates a fresh array that includes the elements that have been extracted.
Examples of JavaScript Array slice Method
Let’s explore the array slice method through some illustrative examples.
Example1: Array slice method without a parameter
In this illustration, we will extract a portion of an array without providing any arguments.
Code:
Example
let myArray = ["Apple", "Banana", "Orange", "Mango"];
let res = myArray.slice();
console.log(res);
Output:
[ 'Apple', 'Banana', 'Orange', 'Mango' ]
Explanation:
In the code above, we have defined a variable called myArray with the let keyword. This array comprises various fruit names. We applied the slice method to myArray and assigned the outcome to the variable res, which we subsequently output to the console. Since we invoked the slice method without any arguments, it will create a copy of the entire array in its original form.
Example 2: Array slice method with an index number
In this illustration, we will extract a portion of an array by specifying a single index number. This index number will serve as the starting point, and the operation will yield the elements from the array beginning at that specified index.
Code:
Example
let myArray = ["Apple", "Banana", "Orange", "Mango"];
let res = myArray.slice(3);
console.log(res);
Output:
[ 'Mango' ]
Explanation:
In the code snippet above, we created a variable named myArray that contains four string elements. We utilized the slice method with a single argument on myArray and assigned the outcome to the variable res, which we then displayed in the console. The parameter provided is 3, which serves as the index from which the array is sliced, beginning at index 3 and continuing to the end of the array.
Example 3: Array slice method with two index numbers
In this illustration, we will extract a portion of an array by providing two index values. This operation will yield all the elements located between those two specified indices. The element corresponding to the first index will be included, whereas the element at the second index will be omitted.
Code:
Example
let myArray = ["Apple", "Banana", "Orange", "Mango"];
let res = myArray.slice(1,3);
console.log(res);
Output:
[ 'Banana', 'Orange' ]
Explanation:
In the preceding example, we established a variable referred to as myArray that contains string elements. The slice method was employed with two arguments on myArray. We assigned the output to the variable res and displayed it in the console. This operation will extract a portion of the array beginning from index 1 and concluding at index 3.
Example 4: Passing a single negative index value.
In the following example, we will utilize a solitary negative value as an index to retrieve an element.
Code:
Example
var arr = ["AngularJS","Node.js","JQuery","Bootstrap"]
var result = arr.slice(-1);
console.log(result);
Output:
[ 'Bootstrap' ]
Explanation:
In the preceding code, we established an array referred to as arr, which contains four elements. We utilized a negative index value within the slice method and assigned the result to a variable called result. Using a negative index signifies that we are counting the elements from the array's end; thus, by specifying the index as -1, we retrieve the final value of the array.
Example 5: Passing two negative index values.
In this illustration, we will utilize two negative index values to retrieve elements from the specified array.
Code:
Example
var result=arr.slice(-4,-1);
console.log(result);
Output:
[ 'AngularJS', 'Node.js', 'JQuery' ]
Explanation:
In the code above, we created an array called arr that consists of four elements. We utilized two negative indices and assigned the output to a variable named result. The indices -4 and -1 were used. The index -4 refers to the initial element, while -1 points to the final element in the array. Therefore, the operation slice(-4, -1) retrieves the elements from the array that lie between the indices -4 and -1, effectively capturing the last elements.
Uses of slice method:
- Useful in creating a shallow copy of an array: When we call the slice method without passing any arguments, it creates a new array with all the elements from the original array. It is called shallow copy which means the new array references the same objects.
- Useful for converting array-like objects to arrays: When we use slice.call to convert array-like objects (like arguments, NodeLists, etc.) into actual arrays. It is useful when we want to apply array methods that are not available on array-like objects.
- Useful in String Manipulation : We can use the slice method to extract a part of a string. It can be utilized to extract a portion of a string by entering a start and optional end index.
- Useful for getting elements from the end of an array : We can make use of negative indices with the slice method to get an element from the last index of an array. For example, as in slice (-3), we get back the last 3 elements of the array.
Conclusion:
The slice function in an array is a crucial method utilized for retrieving a segment of an array. In this article, we have explored the definition of the slice function, its different approaches to obtaining a portion of an array, and the applications of the slice method.
The slice method in an array serves to create a new array that consists of a section of the original array. It does this without modifying the original array itself. The slice method accepts up to two arguments:
- start: This parameter indicates the index from which to begin extraction. If omitted, the extraction starts at index 0.
- end: This parameter is optional as well, and it denotes the index at which to stop extraction (not inclusive). If this argument is not specified, the method will extract elements until the end of the array.
Here’s a brief example for clarity:
const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
const citrus = fruits.slice(1, 3); // This will return ['Banana', 'Cherry']
In the example above, the slice method is utilized to extract elements starting from index 1 up to, but not including, index 3. As a result, the new array citrus contains 'Banana' and 'Cherry'.
It’s crucial to note that the slice method does not alter the original array, which, in this case, remains unchanged as ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'].
The slice function within an array is used to retrieve a section of the array and creates a new array containing the extracted portion. When a programmer employs the slice function, it leaves the original array unchanged.
- In what ways does slice contrast with splice?
The slice function does not alter the original array; instead, it generates a new array as its output. In contrast, the splice function modifies the original array by either adding, removing, or replacing elements within it.
- In what ways can slice be employed to retrieve the last element from an array or a string?
We have the ability to employ a negative index, which allows us to reference elements starting from the end of the array. For instance, invoking myArray.slice(-1) yields an array containing the final element.
- Is it possible to apply the slice method to strings in addition to arrays?
Certainly! The slice function is applicable to both strings and arrays in JavaScript. Its behavior varies depending on the data type it operates on, yielding different results accordingly. When applied to strings, slice retrieves a portion of characters and provides a new string in return. Conversely, when utilized on arrays, slice extracts a selection of elements and produces a new array.
- Does the slice method create a deep copy or a shallow copy?
The slice function creates a superficial copy. Primitive data types such as numbers, strings, and booleans are duplicated by their actual value, whereas objects and nested arrays are duplicated by reference. Consequently, if we alter a nested object within the copied array, that change will also be visible in the original array, as both arrays are pointing to the same object in memory.