w3resource

JavaScript shift() Method: Array Object

Description

The shift() method is used to remove the first element from an array. This method returns the removed element and changes the length of the array.

Version

Implemented in JavaScript 1.2

Syntax

shift()

Parameters

None

Example:

The following web document displays the fruitslist array before and after removing its first element. It also displays the removed element.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>JavaScript shift() method example</title>
<style type="text/css">
h1 {color:red}
</style>
</head>
<body>
<h1>JavaScript : shift() method</h1>
<script src="array-shift-example1.js"></script>
</body>
</html>

JS Code

var fruitslist = new Array("Orange","Apple","Banana","Chery" );
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode    ("List of Fruits : "+fruitslist); 
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph);
var removeelement=fruitslist.shift();
var newParagraph1 = document.createElement("p"); 
var newText1 = document.createTextNode("The first element of the Fruits List : "+ removeelement); 
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);

View the example in the browser

Practice the example online

JavaScript shift() method example

See also:

JavaScript Core objects, methods, properties.

Previous: JavaScript reverse() Method: Array Object
Next: JavaScript slice() Method: Array Object

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript/object-property-method/array-shift.php