How To Remove First Array Element In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

There are different ways to remove elements from existing arrays in JavaScript, So we are using shift() method to remove first element of an array and Shifting is equivalent to popping, working on the first element instead of the last.

How To Remove First Array Element In JavaScript With Example

The shift() method removes the first item of an array.

Note: This method changes the length of the array and The return value of the shift method is the removed item.

Note: this method will change the original array.

To remove the last item of an array, use the pop() method.

Let's Start 


Example(1)
1.Create array.

var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];


2.Now shift first element from array using shift method so that we need to implement code as below
document.getElementById("demo").innerHTML = languages;

function languages_function() {
    languages.shift();
    document.getElementById("demo").innerHTML = languages;
}


Complete code of removing first elements from an array.
<!DOCTYPE html>
<html>
<head>
    <title>How To Remove First Array Element In JavaScript With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>Removing First Array Element In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <button class="btn btn-primary" onclick="languages_function()">Click it</button>
        <h1 id="demo"></h1>
    </div>
    <br>
</div>
</body>
</html>

<script>
    var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];
    document.getElementById("demo").innerHTML = languages;

    function languages_function() {
        languages.shift();
        document.getElementById("demo").innerHTML = languages;
    }
</script>

 

Related Post