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.



JavaScript: Tips of the Day

Returns the difference (in days) between two dates

Example:

const tips_DiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);
console.log(tips_DiffBetweenDates(new Date('2020-05-13'), new Date('2020-06-05')));

Output:

23