Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Array:shift

From MDC


Contents

[edit] Summary

Removes the first element from an array and returns that element. This method changes the length of the array.

Method of Array
Implemented in: JavaScript 1.2, NES 3.0
ECMA Version: ECMA-262 Edition 3

[edit] Syntax

var firstElement = array.shift();

[edit] Parameters

None.

[edit] Examples

[edit] Example: Removing an element from an array

The following code displays the myFish array before and after removing its first element. It also displays the removed element:

// assumes a print function is defined
var myFish = ["angel", "clown", "mandarin", "surgeon"];
print("myFish before: " + myFish);
var shifted = myFish.shift();
print("myFish after: " + myFish);
print("Removed this element: " + shifted);

This example displays the following:

myFish before: ["angel", "clown", "mandarin", "surgeon"]
myFish after: ["clown", "mandarin", "surgeon"]
Removed this element: angel

[edit] See Also

pop, push, unshift