1. What is splice()
?
The splice()
method in JavaScript is used to change the contents of an array by:
-
Adding elements
-
Removing elements
-
Replacing elements
It modifies the original array (unlike slice()
which returns a new array).
Here’s a visual diagram showing how splice()
works step-by-step — starting from the original array, removing selected elements, and then inserting new elements at the chosen position.
2. Syntax
array.splice(start, deleteCount, item1, item2, ...);
Parameters
-
start → The index where changes begin.
-
deleteCount → Number of elements to remove.
-
item1, item2, ... → (optional) Elements to add at the
start
index.
3. How it Works
Think of splice()
as:
“Go to the position
start
, removedeleteCount
items, and then insert any new items I give you at that same position.”
4. Examples
Example 1: Removing Elements
let fruits = ['apple', 'banana', 'orange', 'mango'];
// Remove 2 elements starting from index 1
let removed = fruits.splice(1, 2);
console.log(fruits); // ['apple', 'mango']
console.log(removed); // ['banana', 'orange']
Example 2: Adding Elements
let fruits = ['apple', 'mango'];
// Start at index 1, remove 0 elements, add 'banana' and 'orange'
fruits.splice(1, 0, 'banana', 'orange');
console.log(fruits); // ['apple', 'banana', 'orange', 'mango']
Example 3: Replacing Elements
let fruits = ['apple', 'banana', 'orange'];
// Start at index 1, remove 1 element, add 'mango'
fruits.splice(1, 1, 'mango');
console.log(fruits); // ['apple', 'mango', 'orange']
Example 4: Remove All from a Certain Index
let numbers = [1, 2, 3, 4, 5];
// Start at index 2, remove all remaining
numbers.splice(2);
console.log(numbers); // [1, 2]
5. Key Points
-
Modifies original array (in-place).
-
Returns an array of removed elements.
-
If
deleteCount
is0
→ no elements are removed (only adding happens). -
If
deleteCount
is omitted → removes everything fromstart
to end. -
Works with any data type in an array.
No comments:
Post a Comment