Published on

Remove first element of Array in JavaScript

Authors

There are multiple ways in which you can remove the first element of the array in JavaScript.

Here are some of the most common ones

Using Slice method

slice() method is used to create a new array based on the existing array (some portion of it)

And it does not mutate the array. Meaning it returns a new array containing the extracted elements without modifying the original array.

Syntax

It has a straightforward syntax.

// const exampleArray = [1, 2, 3, 4, 5];
exampleArray.start(start, end)
  • start: From this index, it'll start copying.
  • end: Until this index, it'll copy. It is optional; if we don't provide it, then it means it'll process until the end

Usage

const exampleArray = [1, 2, 3, 4, 5];
const newArray = exampleArray.slice(1, 4); //  [2, 3, 4]

It can also handle negative indexing like this:

const exampleArray = [1, 2, 3, 4, 5];
const lastThreeElements = exampleArray.slice(-3); // [3, 4, 5]

Issues with Slice()

slice() method in JavaScript creates a shallow copy of the array.

It means that if the array contains nested objects or array then those things share the references (both original and new array)

Happy copying elements!