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

What is JSON? Know how it Works with Examples

Learn what JSON is and how it works with examples in this comprehensive guide. Discover the basics of JSON syntax, its applications, and why it has be...

What is currying function in JavaScript ?

Currying function in JavaScript allows you to transform a function that takes multiple arguments into a series of functions that each take one arg.

What are the Different Data Types in JavaScript

A web scripting language is called JavaScript. It contains its own data types, much like any other computer language. The type of data that a variable...

Difference Between == and === in JavaScript

Learn the Difference Between == and === in JavaScript. Discover how each operator compares values and data types, and when to use them in code.

What is memoization?

Memoization is a programming technique that improves efficiency by caching results of expensive function calls. Learn more about it here.