JavaScript splice() method
The splice()
method in JavaScript is used to add, remove, or replace elements in an array. It modifies the original array and returns an array containing the removed elements (if any). This method can insert elements at any position, remove elements from any position, or do both.
Syntax:
start
: The index at which to start modifying the array.deleteCount
: The number of elements to remove from the array. If0
, no elements will be removed.item1, item2, ...
(optional): The elements to add to the array starting from thestart
index. If no elements are specified, the method only removes elements.
Return Value:
- An array of removed elements. If no elements are removed, it returns an empty array.
Key Points:
- Modifies the original array: The
splice()
method alters the array. - Can add, remove, or replace: It can remove elements, add new elements, or replace existing elements, depending on the arguments.
- Returns removed elements: It returns an array of elements that were removed from the original array.
Example 1: Removing elements
Example 2: Adding elements
Example 3: Replacing elements
Example 4: Removing elements without adding new ones
Example 5: Removing all elements from a certain index
Parameters Explained:
start
: Specifies where to start the changes. Can be a positive or negative integer.- If positive, it indicates the index from the start of the array.
- If negative, it indicates the index from the end of the array.
deleteCount
: Determines how many elements to remove.- If
0
, no elements are removed (only adding or replacing occurs). - If omitted, all elements from the
start
index to the end of the array will be removed.
- If
item1, item2, ...
: The new elements to be added at thestart
index. If not specified, no new elements are added.
Example 6: Using negative start
Summary:
splice()
is a powerful method for modifying arrays by adding, removing, or replacing elements. It directly affects the original array and can return the removed elements as a separate array.- The method can be used for multiple purposes, such as removing unwanted elements, inserting new ones, or replacing existing elements at any position in the array.