Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What is the array.slice() method in JavaScript?

Chibuike Nwachukwu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The slice() method in JavaScript returns a shallow copy of an array’s selected portion. It saves this copied portion into a new array but does not modify the original array.

Syntax

array.slice(start, end)

Parameters

The slice() method takes the following parameters:

  • start (optional): The starting index of the copied array.
  • If not supplied, it starts from index 0.
  • If negative, it indicates an offset from the end of the sequence. For example, slice(-2) extracts the last two elements in the sequence.
  • If start is greater than the index range of the sequence, an empty array is returned.
  • end (optional) : The ending index of the copied array. This index is non-inclusive.
  • If not supplied, it extracts to the end of the sequence.
  • If negative, it extracts until the end of the sequence. For example, slice(1,-1) extracts the first element through the second-to-last element in the sequence.
  • If end is greater than the sequence length, slice extracts through to the end of the sequence.

Return value

The function returns a new array containing the copied values.

Code

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

In the code above we have five examples, each using different approaches. As we can see, calling the slice() method on an array and printing its value returns a new array following the condition we specified.

RELATED TAGS

javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring