Skip to content

JavaScript array shift | Method

  • by

Using the JavaScript array shift() Method you can remove the first element of an array. This method removes the first element from an array and returns that removed element.

array.shift()

Note: This method changes the original array.

This method modifies the original array by removing the element from the beginning of the array and shifting all the other elements to a lower index position.

JavaScript array shift

Simple example code removing first element form number and string element arrays. A string, a number, an array, or any other type is allowed in an array.

<!DOCTYPE html>
<html>
<body>

  <script>
    const array1 = [1, 2, 3];
    const firstElement = array1.shift();
    console.log(firstElement)
    console.log(array1);


    let languages = ["English", "Java", "Python", "JavaScript"];
    let first = languages.shift();
    console.log(first);
    console.log(languages);

  </script>

</body>
</html> 

Output:

JavaScript array shift Method

Using the shift() method in the while loop

Where in the example every iteration will remove the next element from an array until it is empty:

const names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];

while( typeof (i = names.shift()) !== 'undefined' ) {
    console.log(i);
}

Output: Andrew, Edward, Paul, Chris, John

Another example

Let’s say you have an array of tasks to be completed, and you want to implement them.

let tasks = ['Task 1', 'Task 2', 'Task 3'];

function removeFirstTask() {
  let firstTask = tasks.shift(); // remove the first task from the array
  return firstTask;
}

console.log(tasks); // ["Task 2", "Task 3"]
console.log(removeFirstTask()); /"Task 1"
console.log(tasks); // ["Task 2", "Task 3"]

Comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading