Course contentsShow
← JavaScript
Lesson 835 of 2,72319. ArraysFree lesson

toSpliced() for Immutable Splicing

Perform splice-like operations that return a new array instead of modifying the original.

toSpliced() for Immutable Splicing

You'll learn how to perform splice-like operations without changing the original array.

What Is toSpliced()?

Remember how splice() is a powerful but mutating method that can remove, insert, or replace elements? The toSpliced() method does the exact same operations, but instead of modifying the original array, it returns a brand new array with the changes applied. Your original array stays completely untouched.

How It Works

toSpliced() accepts the same arguments as splice():

const original = ['a', 'b', 'c', 'd', 'e'];

// Remove 2 elements starting at index 1
const removed = original.toSpliced(1, 2);
console.log(removed);  // ['a', 'd', 'e']
console.log(original); // ['a', 'b', 'c', 'd', 'e'] — unchanged!

You can also insert or replace elements:

const fruits = ['apple', 'banana', 'orange'];

// Insert 'grape' at index 1
const added = fruits.toSpliced(1, 0, 'grape');
console.log(added);   // ['apple', 'grape', 'banana', 'orange']

// Replace 'banana' with 'kiwi' and 'mango'
const replaced = fruits.toSpliced(1, 1, 'kiwi', 'mango');
console.log(replaced); // ['apple', 'kiwi', 'mango', 'orange']

console.log(fruits);   // ['apple', 'banana', 'orange'] — always unchanged

Why Use toSpliced()?

This immutable approach is safer in modern JavaScript development, especially when working with state management or when you need to preserve the original data for comparison or undo functionality.

Key Takeaway: toSpliced() performs splice operations (remove, insert, replace) and returns a new array, leaving the original array completely unchanged — just like toSorted() and toReversed().