What is slice() in JavaScript

What is slice()?

slice() is a method used to copy a portion of an array or string without changing the original.

Think of it like cutting a piece out of a cake — you get the piece, but the original cake stays the same.


Syntax

array.slice(start, end)
string.slice(start, end)
  • start → The index where the extraction begins (inclusive).

    • If omitted → starts from 0.

    • If negative → counts from the end.

  • end → The index where extraction stops (exclusive).

    • If omitted → goes till the end.

    • If negative → counts from the end.


Key Points

  1. Does not modify the original array/string.

  2. Returns a new array (or string in case of strings).

  3. Works with negative indexes.


Array Examples

1) Basic Usage

const fruits = ["apple", "banana", "cherry", "date"];
const sliced = fruits.slice(1, 3);

console.log(sliced);       // ["banana", "cherry"]
console.log(fruits);       // ["apple", "banana", "cherry", "date"] (unchanged)

Here:

  • Starts at index 1"banana".

  • Stops before index 3 → excludes "date".


2) Omitting the end

const colors = ["red", "green", "blue", "yellow"];
console.log(colors.slice(2)); // ["blue", "yellow"]

3) Using Negative Indexes

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(-3));     // [3, 4, 5]
console.log(numbers.slice(1, -1));  // [2, 3, 4]
  • -3 → starts from the 3rd last element.

  • end = -1 → stops before the last element.


4) Copying the Whole Array

const arr = [10, 20, 30];
const copy = arr.slice();

console.log(copy); // [10, 20, 30]
console.log(copy === arr); // false (different array in memory)

String Examples

const text = "JavaScript";
console.log(text.slice(0, 4));  // "Java"
console.log(text.slice(4));     // "Script"
console.log(text.slice(-6));    // "Script"

Difference between slice() and splice()

Feature slice() splice()
Changes original? ❌ No ✅ Yes
Return value New array with extracted items Removed items (also modifies the original array)
Usage Copy part of array/string Add/remove elements in array

Example:

const nums = [1, 2, 3, 4];
nums.slice(1, 3); // [2, 3]  (nums unchanged)
nums.splice(1, 2); // removes 2 elements starting at index 1 → nums becomes [1, 4]

Quick Cheat Sheet

  • Inclusive start index, exclusive end index.

  • Works with arrays and strings.

  • Negative index → counts from end.

  • Good for copying and non-destructive slicing.


No comments:

Post a Comment

What is slice() in JavaScript

What is slice() ? slice() is a method used to copy a portion of an array or string without changing the original . Think of it like cut...