Menu
Coddy logo textTech

Slice

Lesson 15 of 18 in Coddy's Array Methods in JavaScript course.

The slice() method is a non-mutating method that extracts a section of an array and returns a new array containing the extracted elements. It acts like a "copier" for a specific portion of the original array.

Syntax: 

array.slice(startIndex, endIndex);
  • Creates a new array, leaving the original one unmodified.
  • Takes two optional arguments: startIndex (inclusive) and endIndex (exclusive).
  • If startIndex is omitted, it defaults to 0 (beginning of the array).
  • If endIndex is omitted, it extracts elements until the end of the array.
  • Negative values for indices are allowed and count from the end of the array.

Imagine you have a list of numbers as given in the numbers array. Here's how slice() comes in handy:

let numbers = [ 1, 2, 3, 4, 5, 6 ];

let newArray = numbers.slice(1, 4);

console.log(newArray); // Output: [ 2, 3, 4 ]

In above example, it starts extracting element from 1 index and stops at (4-1) index.

challenge icon

Challenge

Easy

You have given an array students has a list of five students enrolling in the course.

Your task is to extract the names of the students who are in the second and third places on the list and log the newly extracted array of these names.

Try it yourself

let students = [ 'Jack', 'Jinee', 'Hook', 'Zohie', 'John' ];

// Write code here

All lessons in Array Methods in JavaScript