The array’s chosen elements are returned as a new array by the slice() method. The slice() method also chooses between a specified start and a specified (not inclusive) end. However, the original array is unaltered by the slice() technique.
JavaScript Array slice() Syntax
The syntax for the JavaScript Array slice() function is as follows:
array.slice(start, end)
Parameters
Here, we look at the parameters for the method slice() in JavaScript
start
It is an optional parameter referring to the starting position. By default, it is 0. In the case of negative numbers, it selects array elements from the array’s end.
The key takeaways about the start parameter include:
- The index is zero-based, from which to begin the extraction.
- An offset from the sequence’s end can be indicated by using a negative index.
- The final two elements of the sequence are taken out by slice(-2).
- Slice begins at index 0 if the start is unspecified.
- An empty array is returned if the start exceeds the sequence’s index range.
end
This parameter, just like, start, is optional. It is responsible for marking the final position and assumes the last element by default. When dealing with negative values, it selects from the arrays’ end.
The key takeaways about the end parameter include:
- The first entry to remove from the returning array by index.
- Slice just extracts till the very end.
- Slice(1,4), for instance, extracts the second element through the fourth element (elements indexed 1, 2, and 3).
- An offset from the sequence’s end can be indicated by using a negative index.
- Slice(2,-1) takes the next-to-last element in the sequence and gets the third element from it.
- Slice extracts all the way to the end of the sequence if the end is left out (arr.length).
- Slice extracts all the way to the end of the sequence if the end is longer than the length of the sequence (arr.length).
What is slice()’s method Return Value?
The JavaScript Array method slice() returns a novel array having the chosen items from the original array. Even if that means all the elements because it is also allowed.
What Browsers does the slice() method Support?
slice() refers to an ECMAScript1 which is an ES1 feature. ES1 is a JavaScript 1997 invention and is fully supported in all browsers, including Firefox, Chrome, Internet Explorer, Safari, Opera, and Edge.
Description of how the slice() method works in JavaScript
The initial array is unaffected by the slice(). It gives back a sparse replica of the original array’s elements. The following is how the original array’s elements are transferred into the returned array:
Slice copies object references for objects into the new array. The same object is referred to by both the original and new arrays. The original and new arrays can both see modifications made to an item.
Slice transfers the values into the new array for strings, integers, and booleans (but not for String, Number, and Boolean objects). The other array is unaffected by changes to the first array’s string, number, or boolean. Also, note that the other array is unaffected if a new element is added to the two arrays.
Objects in the liking of Arrays
Array-like objects and collections can also be transformed into new Arrays using the slice method. You merely associate the method with the item. An illustration of an “array-like object” is the arguments contained within a function.
function list() { return Array.prototype.slice.call(arguments); } const numsVars = list(31,32, 33,34,35,36,37,38); // [31,32, 33,34,35,36,37,38] console.log(numsVars)
The JavaScript function slice() without the start and end parameters
We’ve compiled a list of ten English premier league clubs for this first illustration.
const eplClubs = ["Manchester city","Liverpool FC"," Chelsea FC","Machester United","Aston Villa","Leeds United ","Newcastle United","Brighton FC","Southampton FC","Nottingham Forest"];
We can make a shallow copy of that array using the slice() technique.
eplClubs.slice()
We will then see all of the components from the English premier league array copied into this new array when we log the outcome using console.log().
["Manchester city","Liverpool FC"," Chelsea FC","Machester United","Aston Villa","Leeds United ","Newcastle United","Brighton FC","Southampton FC","Nottingham Forest"];
How to use the start parameter with the JavaScript function slice()
Using the optional start parameter, you can specify a beginning point for choosing entries from the array. It’s critical to keep in mind that arrays use zero-based indexing. The final three clubs in the array will be chosen and returned in a new array if the start position is set to index 2 in this example.
const newClubsArr = eplClubs.slice(2); console.log(newClubsArr) The original array was not modified, as seen in this example. const eplClubs = ["Manchester city","Liverpool FC"," Chelsea FC","Machester United","Aston Villa","Leeds United ","Newcastle United","Brighton FC","Southampton FC","Nottingham Forest"]; const newClubsArr = eplClubs.slice(2); console.log("Original: ", eplClubs) console.log("New: ", newClubsArr)
Additionally, negative indexes can be used to begin removing elements from the array’s tail. To choose the last two English premier league clubs in the array and return them to a new array, we will set the start position in this example to -2.
const eplClubs = ["Manchester city","Liverpool FC"," Chelsea FC","Machester United","Aston Villa","Leeds United ","Newcastle United","Brighton FC","Southampton FC","Nottingham Forest"]; const newClubsArr = eplClubs.slice(-2); console.log(newClubsArr)
An empty array is subsequently returned if the start parameter is higher than the array’s last index.
const newClubsArr = eplClubs.slice(15); console.log(newClubsArr)
Using the start and end parameters when using the JavaScript function slice()
The slice() method will extract components from the start location through the end position if an end position is given. The extracted elements for the new array won’t contain the end position. We have supplied a start index of 2 and an end index of 4 for this example.
Due to the end position not being included in the extracted components, the new returned array will only contain the English premier league clubs at indexes 2 and 3.
const eplClubs = ["Manchester city","Liverpool FC"," Chelsea FC","Machester United","Aston Villa","Leeds United ","Newcastle United","Brighton FC","Southampton FC","Nottingham Forest"]; const newClubsArr = eplClubs.slice(2,4); console.log()
Example: Selecting elements
const laptops = ["IBM", "Lenovo", "Toshiba", "Apple", "Chrome Book"]; const resVal = laptops.slice(1, 3); console.log(resVal)
Example: Using negative values to select elements
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const myFavorite = fruits.slice(-3, -1); console.log(myFavorite)
Example: Exploring slice() method in JavaScript
const computerCompanies = ['Microsoft', 'Facebook', 'Google', 'Apple', 'Amazon']; console.log(computerCompanies.slice(2)); // expected output: Array ["Google ", " Apple ", " Amazon "] console.log(computerCompanies.slice(2, 4)); // expected output: Array ["Google ", " Apple "] console.log(computerCompanies.slice(1, 5)); // expected output: Array ["Facebook ", " Google ", " Apple ", " Amazon "] console.log(computerCompanies.slice(-2)); // expected output: Array ["Apple ", " Amazon "] console.log(computerCompanies.slice(2, -1)); // expected output: Array ["Google ", " Apple "] console.log(computerCompanies.slice()); // expected output: Array ["'Microsoft'", " Facebook ", " Google ", " Apple ", " Amazon "]
Example : Objects as Array Elements in JavaScript’s slice()
The array’s elements are shallowly copied by the slice() method as follows:
- References to objects are copied to the new array. (For instance, a nested array) As a result, any modifications to the referenced object are reflected in the newly returned array.
- The values of strings and numbers are also copied to the new array.
let student = { name: "Green", age: 17, }; let arrVals = [student, "Nepal", "Headteacher"]; let new_arr = arrVals.slice(); // original object console.log(arrVals[0]); // { name: 'Green', age: 17 } // updating novel changes to the object in new array new_arr[0].name = "Joy"; // changes are reflected console.log(arrVals[0]); // { name: 'Joy', age: 17 }
Example: Using slice
In the example below, slice builds a new array, weddingCar, from myDreamCar. Both make mention to the thing mercesBenz. Both arrays update to purple when the color of mercesBenz is altered.
// Using slice, create weddingCar from mercesBenz. const mercesBenz = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; const myDreamCar = [mercesBenz, 2, 'cherry condition', 'purchased 1997']; const weddingCar = myDreamCar.slice(0, 2); // Display the values of myDreamCar, weddingCar, and the color of mercesBenz // referenced from both arrays. console.log(' my dream car is = ', myDreamCar); console.log(' my wedding car is = ', weddingCar); console.log('myDreamCar[0].color = ', myDreamCar [0].color); console.log(' weddingCar[0].color = ', weddingCar [0].color); // Change the color of mercesBenz. mercesBenz.color = 'grey'; console.log('The new color of my Mercedes Benz is ', mercesBenz.color); // Display the color of mercesBenz referenced from both arrays. console.log('myDreamCar[0].color = ', myDreamCar[0].color); console.log(' weddingCar[0].color = ', weddingCar[0].color);
Example: Negative index slice() in JavaScript
You are also free to use negative start and end indices with JavaScript. Actually, the final element’s index is -1, the next-to-last element’s index is -2, and so on.
const codeLanguages = ["JavaScript", "Python", "C", "C++", "Java"]; // this code snippet slices the provided array from start to second-to-last let codeArr = codeLanguages.slice(0, -1); console.log(codeArr); // [ 'JavaScript', 'Python', 'C', 'C++' ] // this code snippet slices the given array from third-to-last let codeArrOne = codeLanguages.slice(-3); console.log(codeArrOne); // [ 'C', 'C++', 'Java' ]
Example: JavaScript method slice() in action
let codeLanguages = ["JavaScript", "Python", "C", "C++", "Java"]; // code snippet for slicing the array from start to end of the given array let newCodeArr = codeLanguages.slice(); console.log(newCodeArr); // [ 'JavaScript', 'Python', 'C', 'C++', 'Java' ] //this code snippet is responsible for slicing from the third element in the subsequent array let newCodeArrOne = codeLanguages.slice(2); console.log(newCodeArrOne); // [ 'C', 'C++', 'Java' ] // this code snippet slices from the second element to fourth element in the array provided let newCodeArrTwo = codeLanguages.slice(1, 4); console.log(newCodeArrTwo); // [ 'Python', 'C', 'C++' ]
Conclusion
When you first start learning JavaScript, it may be challenging to fully grasp how the method slice() is used in your daily activities. As a result, with the help of examples, we have learned about the JavaScript Array slice() technique in this article. In fact, Slice() method creates a new array object by making a shallow duplicate of a specific area of the array provided. Where start and end indexes point to the respective array’s items, the subset is chosen from start to end without including the end. However, the initial array won’t be changed.