What is Splice in JavaScript ?
Last Updated :
06 Feb, 2024
In JavaScript, splice()
is a method that can be used to change the contents of an array by removing or replacing existing elements and/or adding new elements. It is a versatile method that allows you to modify arrays in-place.
Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...);
Parameters:
startIndex
: The index at which to start changing the array. If negative, it counts from the end of the array.
deleteCount
: The number of elements to remove from the array, starting at startIndex
. If set to 0
, no elements are removed.
item1, item2, ...
: The elements to add to the array, starting at the startIndex
.
Example: Here is the basic example of the Array splice() method.
Javascript
let webDvlop = [ "HTML" , "CSS" , "JS" , "Bootstrap" ];
console.log(webDvlop);
let removed = webDvlop.splice(2, 1, 'PHP' , 'React_Native' )
console.log(webDvlop);
console.log(removed);
webDvlop.splice(-2, 0, 'React' )
console.log(webDvlop)
|
Output
[ 'HTML', 'CSS', 'JS', 'Bootstrap' ]
[ 'HTML', 'CSS', 'PHP', 'React_Native', 'Bootstrap' ]
[ 'JS' ]
[ 'HTML', 'CSS', 'PHP', 'React', 'React_Native', 'Bootstrap' ]
Share your thoughts in the comments
Please Login to comment...