JavaScript's slice() function returns a shallow duplicate of the array's chosen area. It does not change the original array; it simply stores the copied piece in a new array.


array.slice(start, end)


The following parameters are passed to the slice() method:

  1. start (optional): The array's duplicated copy's initial index.
    • If nothing is given, it begins at index 0.
    • If the value is negative, the offset from the sequence's end is indicated. Slice(-2) removes the final two items of the sequence, for instance.
    • An empty array is returned if start exceeds the sequence's index range.
  2. end (optional): The array's final index after being copied. This list is not exhaustive.
    • It extracts to the end of the sequence if nothing is provided.
    • Negative results result in extraction up to the end of the sequence. For instance, slice(1,-1) pulls the
    • first element from the sequence via the next-to-last member.
    • Slice extracts all the way to the sequence's end if end is longer than the length of the sequence.

Return value

The duplicated values are contained in a new array that the function returns.

const countries = ['USA', 'NIGERIA', 'GHANA', 'GERMANY', 'CHINA'];

// expected output: Array ['USA', 'NIGERIA', 'GHANA', 'GERMANY', 'CHINA']

console.log(countries.slice(1, 4));
// expected output: Array ['NIGERIA','GHANA', 'GERMANY']

console.log(countries.slice(2, 4));
// expected output: Array ['GHANA', 'GERMANY']

// expected output: Array ['GHANA', 'GERMANY', 'CHINA]

console.log(countries.slice(1, -1));
// expected output: Array ['NIGERIA', 'GHANA', 'GERMANY']


There are five instances in the code above, each employing a unique strategy. We can see that by using the slice() method on an array and publishing its value, a new array that satisfies the criteria we set is produced.

Recommended Posts

View All

JavaScript Immediately-invoked Function Expressions (IIFE)

Learn about Immediately-invoked Function Expressions (IIFE) in JavaScript. Understand their benefits and how to use them effectively. Start coding now

JavaScript's Lambda and Arrow Functions

Lambda and arrow functions in JavaScript allow for concise and elegant code. Learn how to use them to streamline your code and improve readability.

Learn JavaScript Closures with Code Examples

Master JavaScript closures with code examples! Our comprehensive guide explains how closures work and how to use them in your code. Start learning now...

Describe Singleton Pattern In JavaScript

The singleton pattern is a popular design pattern one for JavaScript. It offers a means of organizing the code into a logical chunk that can be reache...

What is the purpose of the array splice method

The array splice method in JavaScript can be used to add or remove elements from an array. Learn how to use it and what its purpose is in this guide.