People commonly use these methods to manipulate arrays. Understanding how to use these methods can help you write more efficient and effective code. I
What is an Array?
let’s take a moment to review what an array is. In JavaScript, an array is a special type of object that stores a collection of values. Arrays can hold any data type, including numbers, strings, and objects. To declare an array, you use square brackets ([]), and separate each item in the array with a comma.
Slice()
Developers use the slice() method to extract a portion of an array and obtain it as a new array. This method does not modify the original array. When using the slice() method, two arguments need to be provided: the starting index and the ending index (non-inclusive) of the portion of the array that developers want to extract.
const myArray = [1, 2, 3, 4, 5];
const newArray = myArray.slice(1, 3);
console.log(newArray); // [2, 3]
In this example, we start at index 1 (which is the second item in the array, since arrays are zero-indexed), and end at index 3 (which is the fourth item in the array). The slice() method returns a new array containing the items from the original array at those indexes.
Splice()
This method is used to add or remove items from an array. Unlike slice(), splice() modifies the original array. The splice() method takes three arguments: the starting index, the number of items to remove, and any new items to add.
const myArray = [1, 2, 3, 4, 5];
myArray.splice(1, 2, 6, 7);
console.log(myArray); // [1, 6, 7, 4, 5]
In this example, we start at index 1 (the second item in the array), remove 2 items, and add the numbers 6 and 7. The splice() method modifies the original array in place.
Differences Between Slice() and Splice()
The main difference between them is that slice() returns a new array, while splice() modifies the original array. Additionally, slice() does not modify the original array, while splice() can both remove and add items to the array.
Another difference between the two methods is the number of arguments they take. slice() takes two arguments (start and end), while splice() takes three or more arguments (start, deleteCount, and any new items to add).
Combining Slice() and Splice()
Although slice() and splice() are often used separately, they can also be used together to manipulate arrays in more complex ways. For example, you could use slice() to extract a portion of an array, modify the new array using splice(), and then insert the modified items back into the original array using splice().
Conclusion
these are two important methods for manipulating arrays in JavaScript. slice() is used to extract a portion of an array and return it as a new array, while splice() is used to add or remove items from an array.
Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs
Read More
https://scribblersden.com/what-are-template-strings/