JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow Array Right Arrow splice()

splice()  Array  instance method


Adds and/or removes elements from within an array.


Signature Description
anArray.splice(index [,integer] [,element1[, ...[, elementN]]])Adds and/or removes elements from within an array.


Parameter Description
indexThe index at which to start modifications from or number of elements from the end for negative values.
integerAn integer indicating how many elements to remove or 0 for no removal. If not specified all elements after index will be removed.
elementNAny elements to add to the array.


The code below creates an array then adds and removes elements as per the comments.

// Create an array with four elements.
var weekDays = ['Mon', 'Tues', 'Wed', 'Thurs'];

 Remove element 2 and 3 from the array using the splice() method. The first 
 number within the brackets is the starting index to delete from, remember
 indexing starts from 0. The second number is number of elements to delete.
alert(weekDays); // Array now holds ['Mon', 'Thurs'].

// Add two elements starting from index 1 splice() method. 
alert(weekDays); // Array now ['Mon', 'Sat', 'Sun', 'Thurs'].

 Remove element 2 and 3 from the array and replace with new values using the 
 splice() method.
alert(weekDays); // Array is ['Mon', 'Tues', 'Wed', 'Thurs'].

 Only first parameter entered so all elements after index removed using the 
 splice() method.
alert(weekDays); // Array is ['Mon'].

Press the button below to action the above code:

Related Tutorials

JavaScript Intermediate Tutorials - Lesson 1 - Arrays


go to home page Homepage go to top of page Top