JavaScript Remove First Element From Array

JavaScript Remove First Element From Array | Developers frequently encounter the usual programming paradigm of removing entries from an array. Let’s examine the JavaScript method for removing the first element from an array. The shift() and splice() are two JavaScript methods in the Array.prototype that can be used to remove the first element of the array in JS. Also see:- How to add elements at the beginning of the array in JavaScript.

JavaScript Remove First Element From Array Using shift() Method

The shift() does not require any arguments. It both removes the component from the array and returns the array’s first element. We can use the array.shift() technique in JavaScript to get rid of the array’s initial element. The length of an array is modified with the shift() technique. The deleted element from an array is returned by the array shift() function. Everything is moved to the left using the shift() technique.

Syntax:-
array.shift()

let arr = ['Java', 'Python', 'C++', 'JavaScript', 'HTML']
removedEle = arr.shift();

console.log('Removed Element: ', removedEle);
console.log('Remaining array: ', arr);

Output:-

Removed Element: Java
Remaining array: [ ‘Python’, ‘C++’, ‘JavaScript’, ‘HTML’ ]

Remove First Element From Array JavaScript Using splice()

The splice() function, which we shall examine next, is slower than the shift() method. splice(start, deleteCount)

We’ll need to provide two parameters to splice in order to delete the first element (). Start, which is also the index of the object we’re removing, is the first argument. The start is 0 in this instance since the first item is being removed.

Syntax:-
array.splice(index, howmany, item1, ….., itemX)

The eliminated elements are included in the new array that the splice() method returns. You notice that the splice method outputs an array of eliminated elements rather than a single value. It may consist of one or more array elements.

let arr = ['Sun', 'Venus', 'Earth', 'Mars']
removedEle = arr.splice(0, 1);

console.log('Removed elements array: ', removedEle);
console.log('Remaining array', arr);

Output:-

Removed elements array: [ ‘Sun’ ]
Remaining array [ ‘Venus’, ‘Earth’, ‘Mars’ ]

Whenever it boils down to it, JavaScript makes it rather simple to remove the first element from an array of JavaScript. To remove elements from the initial index, a particular location, and the last index, utilize various function combinations.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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