In this article, you will learn about the JavaScript Array built-in method Array.prototype.splice()
. How did this method work in javascript?
The Array.prototype.splice()
method is used to add/remove elements to/from the given array. And it returns an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
array.splice(start, deleteCount, item1, Item2,….itemN);
This method takes 3 parameters as given below:
start > array.length
, it does not remove anything from the array. If the start
is negative, it will start from the backwardstart
. If deleteCount
is not passed as an argument or is greater than the number of elements left in the array, it deletes all elements from start to end. If deleteCount
is 0 or negative, no elements are removed from the array.The splice()
method overwrites the original array.
Here are some examples of Array.prototype.splice()
method:
const language = ["Java", "C#", "Go", "JavaScript", "Python"];
console.log(language.splice(2, 0, "JQuery"));
//No element is removed, an empty array is returned
// Output => []
console.log(language)
//Add "JQuery" at the index 2
//Output => ["Java", "C#", "JQuery", "Go", "JavaScript", "Python"]
const language = ["Java", "C#", "Go", "JavaScript", "Python"];
console.log(language.splice(2, 0, "JQuery", "ASP.NET Core"));
//No element is removed, an empty array is returned
// Output => []
console.log(language)
//Add "JQuery" at the index 2
//Output => ["Java", "C#", "JQuery", "ASP.NET Core", "Go", "JavaScript", "Python"]
const language = ["Java", "C#", "Go", "JavaScript", "Python"];
console.log(language.splice(2, 1));
//one element is removed and returns in the array
// Output => ["Go"]
console.log(language)
//Output => ["Java", "C#", "JavaScript", "Python"]
const language = ["Java", "C#", "Go", "JavaScript", "Python"];
console.log(language.splice(2, 1, "ASP.NET Core"));
//one element is removed and returns in the array
// Output => ["Go"]
console.log(language)
//["Go"] removed and "ASP.NET Core" inserted
//Output => ["Java", "C#", "ASP.NET Core", "JavaScript", "Python"]
const language = ["Java", "C#", "Go", "JavaScript", "Python"];
console.log(language.splice(-2, 1));
//one element is removed and returns in the array
// Output => ["JavaScript"]
console.log(language)
//["JavaScript"] removed
//Output => ["Java", "C#", "Go", "Python"]
const language = ["Java", , "C#", "Go", "JavaScript", "Python"];
console.log(language.splice(1, 2));
//one element is removed and returns in the array
// Output => [empty, 'C#']
console.log(language)
//["JavaScript"] removed
//Output => ["Java", "Go", "JavaScript", "Python"]
I hope this article will help you to understand the javascript Array built-in method Array.prototype.splice().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments