Advertisement
The splice() method in JavaScript is used to add, remove, or replace elements within an array. Unlike slice(), which creates a shallow copy and does not alter the original array, splice() modifies the original array in place and returns an array containing the removed elements.
#### Syntax
1array.splice(start, deleteCount, item1, item2, ...)- start: The index at which to start changing the array.
- deleteCount: (Optional) The number of elements to remove from the array. If omitted, all elements from the start index to the end of the array will be removed.
- item1, item2, ...: (Optional) Elements to add to the array, starting at the start position.
#### Examples
1let arrayIntegersOriginal1 = [1, 2, 3, 4, 5];
2
3let arrayIntegersOriginal2 = [1, 2, 3, 4, 5];
4
5let arrayIntegersOriginal3 = [1, 2, 3, 4, 5];
6
7// Remove the first two elements
8
9let arrayIntegers1 = arrayIntegersOriginal1.splice(0, 2);
10// arrayIntegers1: [1, 2]
11// arrayIntegersOriginal1 (after): [3, 4, 5]
12
13// Remove all elements from index 3 onwards
14
15let arrayIntegers2 = arrayIntegersOriginal2.splice(3);
16// arrayIntegers2: [4, 5]
17// arrayIntegersOriginal2 (after): [1, 2, 3]
18
19// Remove 1 element at index 3, then insert "a", "b", "c" at that position
20
21let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c");
22// arrayIntegers3: [4]
23// arrayIntegersOriginal3 (after): [1, 2, 3, "a", "b", "c", 5]Note:
- The splice() method modifies the original array.
- It returns an array containing the elements that were removed (if any).
- You can use it both to remove and insert elements in a single operation.
Advertisement
JavaScript Coding Exercise 7
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement