What is splice() in JavaScript

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

  1. start → The index where changes begin.

  2. deleteCount → Number of elements to remove.

  3. item1, item2, ... → (optional) Elements to add at the start index.


3. How it Works

Think of splice() as:

“Go to the position start, remove deleteCount 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 is 0 → no elements are removed (only adding happens).

  • If deleteCount is omitted → removes everything from start to end.

  • Works with any data type in an array.

No comments:

Post a Comment

What is slice() in JavaScript

What is slice() ? slice() is a method used to copy a portion of an array or string without changing the original . Think of it like cut...