JavaScript .splice()
Published Jun 22, 2021Updated Jul 30, 2022
Contribute to Docs
The .splice() method modifies an array in place by inserting, removing, and/or replacing array elements then returning an array of removed elements.
Syntax
array.splice(start, itemCount, item1, item2, ..., itemN);
start: The array index at which the insertion and/or removal is to begin.itemCount(optional): The number of elements in the array to remove beginning atstart.item1, item2,..., itemN(optional): The elements that will be inserted into the array atstart.
If only the start index is provided then it will remove all the elements from start to the end of the array.
A negative start value indicates an offset from the end of the array.
Example
The following example adds 'Saturday' and 'Sunday' to the end of the daysOfWeek array:
const daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];daysOfWeek.splice(5, 0, 'Saturday', 'Sunday');console.log(daysOfWeek);
The output will look like this:
['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
Codebyte Example
The following example removes the months and then replaces 'Wednesday' with 'WEDNESDAY' in the daysOfWeek array:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours