/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: shift()

[this page | pdf | back links]

The shift() method (when applied to a JavaScript array) removes the first element of the array and returns that element.

 

It has the following syntax with no parameters. It returns the relevant object or primitive that was at the relevant place in the original array.

 

array.shift()

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var h = [-1, 2, 3];
var y = h.shift();
document.getElementById("Example").innerHTML =
  'var h = [-1, 2, 3];<br>' +
  'var y = h.pop();<br>' +
  'var x = y + "|" + h;';
document.getElementById("Result").innerHTML = y + "|" + h;
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArrayShift() {
  var h = [1, 2, 3]; return !!h.shift;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile