Javascript: Remove element from beginning of array

Often there is a requirement to delete an element at the start of an array in javascript. This article will discuss removing the first element from a javascript array using simple methods and example illustrations.

Table of Contents:-

Javascript remove element from beginning of an array using shift()

Javascript’s shift() method removes the first element of the array and will return the removed element. The shift() method will change the length of the array.

Example:-

Remove first element from the array [1,4,9,16,25]

Code:-

let numArray = [1,4,9,16,25];
numArray.shift(); 
console.log("Array Elements After Removing First Element: " + numArray);

Output:-

Array Elements After Removing First Element: 4,9,16,25

Javascript remove element from beginning of an array using slice()

Javascript’s slice(startIndex, endIndex) method returns a shallow copy of a portion of the calling array into a new array object based on indexes passed as arguments. The index is zero-based.

  • startIndex: is the index to start the extraction.
  • endIndex: is the index to end the extraction. This argument is optional; therefore, if not present, it means to extract array elements till the end of the array.

Example:-

Remove first element from the array [1,4,9,16,25]

Code:-

let numArray = [1,4,9,16,25];
numArray=numArray.slice(1);
console.log("Array Elements After Removing First Element: " + numArray);

Output:-

Array Elements After Removing First Element: 4,9,16,25

Explanation:-

Here, slice(1) will extract the elements from the 1st index (including element at 1st index) till the end of the array where the index starts from 0.

Javascript remove element from beginning of array using splice()

Javascript’s splice(start, deleteCount, item1, item2….) method is used to modify the elements of an array. The splice() method can remove, replace or/and add new elements to the array.

  • start: is the index from where the change in the array needs to be done.
  • deleteCount: is the number of elements to be removed from the array. This argument is optional.
  • item1,item2,… : are the elements that need to be added. These arguments are optional.

Example:-

Remove first element from the array [1,4,9,16,25]

Code:-

let numArray = [1,4,9,16,25];
numArray.splice(0,1);
console.log("Array Elements After Removing First Element: " + numArray);

Output:-

Array Elements After Removing First Element: 4,9,16,25

Explanation:-

The splice(0,1) method in above code will delete 1 element(second argument) starting from 0th index(first argument).

Read More:

I hope this article helped you to remove an element at the beginning of an array in javascript. Good Luck !!!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top