splice() for Inserting Elements
What you'll learn: How to use splice() to insert new elements anywhere in an array without removing anything.
In the previous lesson, you learned how splice() can remove elements. But here's the powerful part: splice() can also insert elements at any position without deleting anything. You simply pass 0 as the delete count.
The Insertion Syntax
array.splice(startIndex, 0, item1, item2, ...);
The key is that second parameter: when you pass 0, you're telling splice() "don't delete anything, just insert here."
How It Works
Think of splice() for insertion like squeezing new books onto a shelf between existing ones—everything shifts to make room, but nothing gets removed.
const fruits = ['apple', 'banana', 'grape'];
// Insert 'orange' and 'kiwi' at index 1 (between apple and banana)
fruits.splice(1, 0, 'orange', 'kiwi');
console.log(fruits);
// ['apple', 'orange', 'kiwi', 'banana', 'grape']
Multiple Insertions
You can insert as many elements as you want in one call:
const numbers = [1, 5];
// Insert three numbers at index 1
numbers.splice(1, 0, 2, 3, 4);
console.log(numbers);
// [1, 2, 3, 4, 5]
Inserting at the End
You can use the array's length as the start index to append elements:
const letters = ['a', 'b'];
letters.splice(letters.length, 0, 'c', 'd');
console.log(letters);
// ['a', 'b', 'c', 'd']
Key Takeaway: Use splice(index, 0, ...items) to insert elements at any position in an array—the 0 delete count means "insert only, don't remove anything."