The Array.toSpliced()
method is a new JavaScript function introduced in ECMAScript 2023 (ES14). It creates a shallow copy of an array with modifications specified by the provided parameters, without changing the original array.
Syntax
let newArray = arr.toSpliced(start, deleteCount, ...items);
Parameters
Parameter | Description |
---|---|
start | (Required) The index at which to begin changing the array. Negative values count from the end of the array. |
deleteCount | (Optional) The number of elements to remove from the array. If 0 , no elements are removed. If omitted, all elements from start to the end are removed. |
…items | (Optional) Elements to add to the array at the start index. If no elements are provided, only removal occurs. |
Return Value
The toSpliced()
method returns a new array that reflects the modifications specified. The original array remains unchanged.
Example 1: Removing Elements
let arr = [10, 20, 30, 40, 50]; let newArr = arr.toSpliced(1, 2); console.log(newArr); // Output: [ 10, 40, 50 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
The method removes two elements starting at index 1
, returning a new array while preserving the original array.
Example 2: Adding Elements
let arr = [10, 50]; let newArr = arr.toSpliced(1, 0, 20, 30, 40); console.log(newArr); // Output: [ 10, 20, 30, 40, 50 ] console.log(arr); // Output: [ 10, 50 ]
Example 3: Replacing Elements
let arr = [10, 20, 30, 40, 50]; let newArr = arr.toSpliced(1, 2, 100, 200); console.log(newArr); // Output: [ 10, 100, 200, 40, 50 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Example 4: Clearing an Array
let arr = [10, 20, 30, 40, 50]; let newArr = arr.toSpliced(0, arr.length); console.log(newArr); // Output: [] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Example 5: Using Negative Indices
let arr = [10, 20, 30, 40, 50]; let newArr = arr.toSpliced(-2, 1); console.log(newArr); // Output: [ 10, 20, 30, 50 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Example 6: Returning a Copy Without Modifications
let arr = [10, 20, 30, 40, 50]; let newArr = arr.toSpliced(); console.log(newArr); // Output: [ 10, 20, 30, 40, 50 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Supported Browsers
Browser | Support |
---|---|
Chrome | 110+ |
Firefox | 109+ |
Safari | 16.4+ |
Edge | 110+ |
Opera | 96+ |
Internet Explorer | Not Supported |