Codectionary / Developer documentation / JavaScript

slice() and splice()

slice() returns a shallow copy of a portion of an array as a new array, without modifying the original - useful for extracting a section. splice() modifies the original array in place by removing, replacing, or inserting elements at a specific position, and returns the removed elements.

Syntax

arr.slice(start, end)
arr.splice(start, deleteCount, ...items)

Examples

slice() - Non-Mutating Extraction

Extracting a portion of an array without changing the original.

const fruits = ["apple", "banana", "cherry", "date", "elderberry"];

console.log(fruits.slice(1, 3));  // ["banana", "cherry"] - end index excluded
console.log(fruits.slice(2));      // ["cherry", "date", "elderberry"] - to the end
console.log(fruits.slice(-2));     // ["date", "elderberry"] - last 2 elements
console.log(fruits);               // original array is unchanged

splice() - Mutating Removal

Removing elements from an array, modifying it in place.

const numbers = [1, 2, 3, 4, 5];
const removed = numbers.splice(1, 2); // start at index 1, remove 2 elements

console.log(removed);  // [2, 3] - the removed elements
console.log(numbers);  // [1, 4, 5] - original array is mutated

splice() - Inserting and Replacing

Using splice() to insert new elements or replace existing ones.

const colors = ["red", "green", "blue"];

// Insert without removing (deleteCount = 0)
colors.splice(1, 0, "yellow");
console.log(colors); // ["red", "yellow", "green", "blue"]

// Replace an element
colors.splice(2, 1, "purple");
console.log(colors); // ["red", "yellow", "purple", "blue"]

Best practices

  • Use slice() whenever you want a new array without mutating the original - it is the safer, more predictable choice
  • Use splice() specifically when you need to remove or insert elements at a specific position in place
  • Remember slice()'s end argument is exclusive - slice(1, 3) returns indices 1 and 2, not 3
  • Save splice()'s return value if you need the removed elements - it returns them as a new array

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation