JavaScript toSpliced Function Explained with Examples

javascript tospliced function

The toSpliced function creates a new array without changing the original array in JavaScript. It returns a copy with new values at defined positions and leaves other elements unchanged.

Understand the toSpliced Function in JavaScript

The toSpliced function returns a new array after you cut and insert values at specific positions.

Here is the syntax:

array.toSpliced(startIndex, deleteCount, item1, item2)
  • startIndex shows the index to start the cut.
  • deleteCount shows how many elements to cut.
  • You add new values after these two arguments.
    The output will be a fresh array with your changes.

It creates a copy and executes your edits in a new array.

Here is a quick example:

const numbers = [1, 2, 3, 4];
const newNumbers = numbers.toSpliced(1, 2, 9, 10);
console.log(newNumbers);

This returns [1, 9, 10, 4] , and the original array stays [1, 2, 3, 4].

You can create changes to data lists for user interfaces or logs.

The Difference Between splice and toSpliced

The splice function edits the original array directly and changes its content while the toSpliced function creates a new array with the change and keeps the original one stay as it.

Here is a table that shows you the key differences:

Aspectsplice (edits in place)toSpliced (creates new array)
Original ArrayChanges directlyRemains the same
Return ValueThe removed elementsA new array with changes
MutabilityMutableImmutable

You can use the splice function for direct edits where you need the change in the original array.

Use the toSpliced function for edits where you must keep the source array unchanged.

Examples

Replace Elements in a Copy:

const fruits = ['apple', 'banana', 'cherry'];
const copy = fruits.toSpliced(1, 1, 'mango');
console.log(copy);

It removes one element at index one, then it adds a new value, and the original stays the same.

Insert Values Without Deletion:

const letters = ['a', 'b', 'c'];
const newLetters = letters.toSpliced(1, 0, 'x', 'y');
console.log(newLetters);

This makes a new array and puts two letters at index one. It keeps the original as it is.

Remove Multiple Values from a Copy:

const data = [10, 20, 30, 40, 50];
const result = data.toSpliced(1, 3);
console.log(result);

This removes three values starting at index one from a copy and keeps the original one.

Advanced Insert and Remove:

const records = [100, 200, 300, 400, 500];
const thisCopy = records.toSpliced(2, 2, 999, 888, 777);
console.log(thisCopy);

This edits a copy with three new values at index two after two removals and leaves the source untouched.

Wrapping Up

You learned what toSpliced does and how it differs from splice.

The toSpliced creates a new array with changes, while splice edits the original array directly.

FAQs

What is JavaScript toSpliced function?

The toSpliced function in JavaScript creates a new array without changing the original array. It works like splice but does not mutate. Example:

const arr = [1, 2, 3, 4];
const newArr = arr.toSpliced(1, 2);
console.log(newArr); // [1, 4]
console.log(arr);    // [1, 2, 3, 4]

What is the syntax of JavaScript toSpliced function?

The syntax is simple and follows this structure:

array.toSpliced(start, deleteCount, item1, item2, ...)
  • start: index where changes start.
  • deleteCount: number of items removed.
  • item1, item2: new items added.

How does toSpliced differ from splice in JavaScript?

splice changes the original array, while toSpliced returns a new one. Example:

const arr1 = [10, 20, 30];
const arr2 = arr1.splice(1, 1);
console.log(arr1); // [10, 30]

const arr3 = [10, 20, 30];
const arr4 = arr3.toSpliced(1, 1);
console.log(arr3); // [10, 20, 30]
console.log(arr4); // [10, 30]

Can JavaScript toSpliced function insert new elements?

Yes, you can insert new elements at any index without altering the original array. Example:

const arr = [5, 10, 20];
const result = arr.toSpliced(1, 0, 15, 18);
console.log(result); // [5, 15, 18, 10, 20]
console.log(arr);    // [5, 10, 20]

Similar Reads

JavaScript valueOf Function: How it Works with Examples

You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…

String Operators in JavaScript: A Complete Guide to Concatenation

String Operators in JavaScript help you work with text. You can join, build, or change strings. Most of what you…

JavaScript Optional Chaining “?”: How it Works with Examples

JavaScript optional chaining lets you access object values without runtime errors. It checks if a property exists before access and…

Math pow in JavaScript : How to Raise Numbers to Power

The Math.pow() function in JavaScript solves one common task. It raises a number to a power. This helps avoid loops…

JavaScript Math tan: The Tangent of an Angle in Radians

JavaScript Math.tan() finds the tangent of an angle in radians. You use it when you need to solve angle-based math.…

JavaScript Object References and Copying for Beginners

Object References in JavaScript mean that variables do not store full objects but only their references in memory. What is…

Bitwise Operators in JavaScript

Bitwise operators work with binary data at the bit level in JavaScript. They process numbers in binary form and return…

JavaScript Math abs(): How It Works with Examples

Some numbers come from user input and other come from math operations. Sometimes, these numbers need to stay positive. The…

How to Use the Ternary Operator in JavaScript

The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…

JavaScript Nullish Coalescing Operator Guide with Examples

The JavaScript nullish coalescing operator (??) gives a default value when a variable is null or undefined. Understand the Nullish…

Previous Article

PHP array_key_last Function: How it Works with Examples

Next Article

What is HTML for Beginners and How it Works for Beginners

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.