Home » Programming » Javascript » Javascript Array Shift

Array.shift() to Remove First Item from JavaScript Array [Examples]

This short tutorial will show you how to use the JavaScript Array.shift() method to remove items from an array, and provide some code examples.

JavaScript Arrays

An array is a variable type which can hold zero or more values within it. Each value in an array has a position, called the index – which is an integer value representing the items position in it’s order of appearance. Indexes start counting at position 0 – so the first item in an array is at index 0, the second item at index 1, and so on.

JavaScript arrays are usually defined using the following syntax:

var myArray = [1, 2, 3]; // Define an array containing the numerical values 1, 2, 3

You can find out more about defining JavaScript arrays in our article – The Best Way to Declare an Array in JavaScript.

Remove The First Item From an Array With The Array.shift() Method

The shift() method will remove the first item (the item at index 0) from an array and return it.

JavaScript Array.shift() Syntax

The syntax for the shift() method is as follows:

array.shift()

Note that:

  • array can be any array type variable
    • It can be empty
  • shift() will remove the element from the array it is called from
  • shift() will return the value of the removed element
    • If the array is empty, a value of undefined will be returned

JavaScript Array.shift() Examples

The following code example shows how the shift() method is used with JavaScript arrays:

var myArray = [1, 2, 3]; // Define an array containing the numerical values 1, 2, 3

console.log(myArray); //  Print the array to the console for inspection

var removedElement = myArray.shift(); // Call the shift() method on the array to remove the first element from the array and assign the value to the variable removedElement

console.log(myArray); // The array will now have the value [2, 3]

console.log(removedElement); // The variable removedElement will contain the value of the element removed from the array

The below example illustrates what happens when shift() is called on an empty array:

var myArray = []; // Define an empty array

var removedElement = myArray.shift();

console.log(removedElement); // removedElement will have a value of undefined

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment