DEV Community

Cover image for Immutable Splice in Javascript
Kurapati Mahesh
Kurapati Mahesh

Posted on • Updated on


Immutable Splice in Javascript

Splice by default mutates/changes/updates inputted array in Javascript. For example:

const test = ['angel', 'clown', 'mandarin', 'sturgeon'];
test.splice(2, 1, 'first');

> ['angel', 'clown', 'first', 'sturgeon']
Enter fullscreen mode Exit fullscreen mode

If you see in above example splice mutates original array.

We can create immutable splice function in Javascript.

Here we go:

function splice(arr, start, deleteCount, ...addItem) {
    const result = [];
    if (start > 0) {
        result.push(...arr.slice(0, start));
    const len = result.length - addItem.length;
    let count = deleteCount <= 0 ? len : len + deleteCount;
    if (arr[count]) {
    return result;

const test = ['angel', 'clown', 'mandarin', 'sturgeon'];

console.log(splice(test, 2, 1, 'drum'));
> ['angel', 'clown', 'drum', 'sturgeon']
> ['angel', 'clown', 'mandarin', 'sturgeon']
Enter fullscreen mode Exit fullscreen mode

test array in above example isn't mutated.

Welcoming suggestions/concerns. Always happy to update article for any use case.

Thank you! Happy experimenting.

💎 Love to see your response

  1. Like - You reached here means. I think, I deserve a like.
  2. Comment - We can learn together.
  3. Share - Makes others also find this resource useful.
  4. Subscribe / Follow - to stay up to date with my daily articles.
  5. Encourage me - You can buy me a Coffee

Let's discuss further.

  1. Just DM @urstrulyvishwak
  2. Or mention

For further updates:

Follow @urstrulyvishwak

Top comments (0)

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓