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.

Syntax

array.slice(start, end)

Parameters

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'];

console.log(countries.slice(0));
// 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']

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

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

Explanation


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 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.

Difference between var and let in JavaScript


Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...

What is the first class function in JavaScript ?


Learn about first-class functions in JavaScript! Find out what they are, how they work, and how they can be used to enhance your coding skills.

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.