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

Harish Kumar · · 133 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 Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Vue 3.5 Release: What's New and Improved?

Vue.js has released version 3.5, bringing a host of exciting new features and optimizations designed to boost developer productivity and improve application performance. This update (...)
Harish Kumar

Understanding useEffect in React: Best Practices and Common Pitfalls

React has become one of the most popular libraries for building user interfaces, and with the introduction of hooks in React 16.8, developers have more powerful tools at their (...)
Harish Kumar

JavaScript Array .filter(): A Comprehensive Tutorial

JavaScript offers several powerful methods to manipulate arrays, and .filter() is one of the most versatile and commonly used. This tutorial will guide you through the basics of (...)
Harish Kumar

Vue 3: Best Practices for Efficient and Scalable Development

Vue.js is a popular JavaScript framework for building user interfaces. It has several features that enhance the development process and performance of applications. This guide (...)
Harish Kumar

JavaScript's Array .forEach() Method Explained: Tips, Tricks, and Examples

The array .forEach() method is one of the most powerful tools in JavaScript, used for executing a provided function once upon an array element. Common applications involve iterating (...)
Harish Kumar