How To Remove The First Element From An Array Using JavaScript

How To Remove The First Element From An Array Using JavaScript

To remove the first element from an array using JavaScript, you can use the shift() function or the splice() method. Let’s check out the details below to get more information, and see how we can do it.

Remove the first element from an array using JavaScript

Using the shift() function

Removing elements from an array is standard programming that programmers have to face. To remove the first element from an array in Javascript, we can easily use the shift() function. This function is already built into Javascript.

Syntax:

shift()

Parameter: None parameter.

Return value: A string, a number, an array, or any other type allowed in an array.

Example: 

In this example, we will create a myArray array with five elements. Then we use the shift() function to remove the first element in myArray by calling myArray.shift(). After that, print out the result on the console.

var myArray = ["Hello,", "I'm", "Learn", "Share", "IT"];
console.log("My array is:", myArray);
 
// Remove the first element "Hello,"
myArray.shift();

console.log("After removing the first element in myArray:", myArray);

Output

My array is: [ 'Hello,', "I'm", 'Learn', 'Share', 'IT' ]
After removing the first element in myArray: [ "I'm", 'Learn', 'Share', 'IT' ]

Using the splice() method

The other simple way to remove the first element from an array is use the splice() method. The splice() method will return an array containing the removed items (If any). It is also a built-in Javascript function and is very helpful for all programmers when they working with an array. We already have an article about how to use the splice() method here.

Example:

var myArray = ["Hello,", "I'm", "Learn", "Share", "IT"];
console.log("My array is:", myArray);

//use splice() method with index to remove is 0 and number to remove is 1
myArray.splice(0, 1);
console.log("After removing the first element in myArray:", myArray);

Output

My array is: ["Hello,", "I'm", "Learn", "Share", "IT"]
After removing the first element in myArray: ["I'm", "Learn", "Share", "IT"]

Summary

In this tutorial, we have explained how to remove the first element from an array using JavaScript by using two methods. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

Maybe you are interested:

Leave a Reply

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