Last Updated on April 17, 2024 by Roshan Parihar
To remove the first element from the array in JavaScript, use the shift()
function without the need to pass any arguments.
You can also use the splice()
function and pass the argument to the index position as zero(0) to delete the first element.
Let’s see some examples given below.
Using shift()
Function in Javascript to Remove First Element From Array
If you want to remove the first element from an array, you can use the shift()
function. It does not require any argument to pass for deletion. See the examples to learn how to remove the first element.
Examples 1
1 2 3 4 5 6 7 8 9 |
<script> function RemoveFirstArrayFn(){ var myArr= [9, 13, 21, 7, 3, 17]; var ItemsFirstRm = myArr.shift(); document.getElementById("myNewArray").innerHTML = "<strong>The new array after first item removal is: </strong>"+myArr; } </script> <button onclick="RemoveFirstArrayFn()">Remove First Element</button> <p id="myNewArray"></p> |
Output
The above example contains the first element as ‘9’. You can click the above button to remove the first element. The output shows that the element is removed.
With splice()
Function to Delete Initial Item
If you want to delete the first item from an array, use the splice()
function of javascript. It takes two arguments in comma separation in which the first argument is the index position of the first item which is zero (0). The second argument is the number of elements to remove from the array which is 1 to delete.
Examples 2
1 2 3 4 5 6 7 8 9 |
<script> function FirstArrSpliceRm(){ var myArr= [9, 13, 21, 7, 3, 17]; var ItemsFirstRm = myArr.splice(0,1); document.getElementById("myNewArray").innerHTML = "<strong>The new array after using <code>splice()</code> is: </strong>"+myArr; } </script> <button onclick="FirstArrSpliceRm()">Remove First Element</button> <p id="myNewArray"></p> |
Output
When you click the button given above, the first element gets deleted. This function is also useful to delete the specified element using its index position.
You May Also Like to Read