Understanding `.slice()` and `.splice()`: JavaScript Array Methods

Harish Kumar · · 1079 Views

In JavaScript, arrays come with numerous built-in methods for manipulation. Two commonly used methods are .slice() and .splice(). While they sound similar, their purposes and behaviors are different. Let’s dive into how each of these methods works.

1. Array.prototype.slice()

Overview:

  1. Purpose: Extracts a section of an array and returns a new array.

  2. Non-mutating: Does not modify the original array.

  3. Syntax:

array.slice(start, end);

Parameters:

  1. start: The index at which the extraction begins (inclusive).

  2. end (optional): The index before which extraction ends (exclusive). If omitted, it slices until the end of the array.

Key Characteristics:

  1. Doesn’t modify the original array.

  2. Returns a shallow copy of the selected elements.

  3. Can handle negative indexes: Negative values count backward from the end of the array.

Examples:

Basic Slicing:

const fruits = ['apple', 'banana', 'cherry', 'date', 'fig'];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'banana', 'cherry', 'date', 'fig'] (original array remains unchanged)

Using Negative Indexes:

const animals = ['lion', 'tiger', 'bear', 'elephant'];
const slicedAnimals = animals.slice(-3, -1);
console.log(slicedAnimals); // ['tiger', 'bear']

2. Array.prototype.splice()

Overview:

  1. Purpose: Changes the content of an array by removing, replacing, or adding elements.

  2. Mutating: Modifies the original array.

  3. Syntax:

array.splice(start, deleteCount, item1, item2, ...);

Parameters:

  1. start: The index at which to start changing the array.

  2. deleteCount: The number of elements to remove.

  3. item1, item2, ... (optional): Elements to add to the array, starting from the start index.

Key Characteristics:

  1. Modifies the original array.

  2. Removes elements if deleteCount is provided.

  3. Can insert new elements if additional elements are provided after deleteCount.

  4. Returns an array of the removed elements.

Examples:

Removing Elements:

const numbers = [10, 20, 30, 40, 50];
const removed = numbers.splice(2, 2);
console.log(removed); // [30, 40]
console.log(numbers); // [10, 20, 50] (original array is modified)

Inserting Elements:.

const colors = ['red', 'green', 'blue'];
colors.splice(1, 0, 'yellow', 'purple');
console.log(colors); // ['red', 'yellow', 'purple', 'green', 'blue']

Replacing Elements:

const letters = ['a', 'b', 'c', 'd'];
letters.splice(1, 2, 'x', 'y');
console.log(letters); // ['a', 'x', 'y', 'd']

3. Comparison of .slice() and .splice()

Feature

.slice()

.splice()

Purpose

Extracts a portion of an array 

Removes, replaces, or adds elements in an array

Mutation

Non-mutating (original array is untouched) 

Mutates the original array

Return Value 

Returns a new array with extracted elements 

Returns an array of removed elements

Insert/Replace 

Cannot insert or replace elements 

Can insert, remove, and replace elements

Usage

Used when a copy or part of an array is needed 

Used when modifying the original array is necessary

Summary

  1. Use .slice() when you need a new array that is a portion of an existing array without changing the original array.

  2. Use .splice() when you need to modify an array by inserting, removing, or replacing elements in the original array.

Both methods are essential tools for array manipulation in JavaScript but should be used appropriately based on whether the original array needs to be modified.

👉 Download Javascript: from ES2015 to ES2023 - eBook

Understanding `.slice()` and `.splice()`: JavaScript Array Methods
0

Please login or create new account to add your comment.

0 comments
You may also like:

How to Use useEffect in React: Tips, Examples, and Pitfalls to Avoid

useEffect is one of the most commonly used hooks in React, enabling you to manage side effects like fetching data, subscribing to events, or manipulating the DOM. However, improper (...)
Harish Kumar

15 Must-Know TypeScript Features to Level Up Your Development Skills

TypeScript has become the go-to tool for developers building scalable, maintainable JavaScript applications. Its advanced features go far beyond basic typing, giving developers (...)
Harish Kumar

JavaScript Best Practices: Tips for Writing Clean and Maintainable Code

JavaScript is one of the most versatile and widely used programming languages today, powering everything from simple scripts to complex web applications. As the language continues (...)
Harish Kumar

Ditch jQuery: Vanilla JS Alternatives You Need to Know

jQuery revolutionized web development by simplifying DOM manipulation, event handling, and animations. However, modern JavaScript (ES6 and beyond) now provides many built-in methods (...)
Harish Kumar

Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained

When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These concepts dictate how data is duplicated (...)
Harish Kumar

A Beginner’s Guide to Efficient Memory Use in JavaScript

Managing memory efficiently in JavaScript applications is essential for smooth performance, especially for large-scale or complex applications. Poor memory handling can lead to (...)
Harish Kumar