3 Example(s) of JavaScript shift function


Description :

JavaScript Shift() function is used to remove the first element of array and return the same element. See code snippet:


JavaScript shift function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
 <button onclick="removeElement()">Remove the first element</button>

<p id="sample"></p>

<script>
var arr= ['abc', 'def', 'ghi', 'jkl'];
document.getElementById("sample").innerHTML = arr;

function removeElement() {
    arr.shift();
    document.getElementById("sample").innerHTML = arr;
}
</script>

</body>
</html>

Output

Description :

JavaScript shift() function return values is the removed item. The output of [100, 1000, 200, 3000].shift() will be 100. See the code snippet:


JavaScript shift function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
  <script>
         var element = [100, 1000, 200, 3000].shift();
         document.write("Removed element is : " + element ); 
      </script>

</body>
</html>

Output

Description :

This example will display all the array element one by one after calling shift function. See the code snippet:


JavaScript shift function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
  <script>
      var array = new Array(20, 31, 2);
      while (array .length > 0)
       {
          var result = array.shift();
          document.write (result.toString() + " ");
       }
      </script>

</body>
</html>

Output