w3resource

JavaScript unshift() Method: Array Object

Description

The unshift() method is used to add one or more elements to the beginning of an array and return the length of the array.

Version

Implemented in JavaScript 1.2

Syntax

arrayName.unshift(element1,element2..., elementN)

Parameters

element1,element2,..., elementN
The elements to add to the front of the array.

Example:

In the following web document, unshift() method adds two elements at the beginning of a given array.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>JavaScript unshift() method example</title>
<style type="text/css">
h1 {color:red}
</style>
</head>
<body>
<h1>JavaScript : unshift() method</h1>
<hr>
<script src="array-unshift-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 the fruits : " + fruitslist);  
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph); 
var ffl = fruitslist.unshift("Grapefruit","Guava");
var newParagraph1 = document.createElement("p"); 
var newText1 = document.createTextNode("New List of the fruits : " + fruitslist); 
newParagraph1.appendChild(newText1); 
document.body.appendChild(newParagraph1); 
var newParagraph2 = document.createElement("p"); 
var newText2 = document.createTextNode("New length of the array : " + ffl);  
newParagraph2.appendChild(newText2); 
document.body.appendChild(newParagraph2); 

View the example in the browser

Practice the example online

JavaScript unshift() method example

See also:

JavaScript Core objects, methods, properties.

Previous: JavaScript toString() Method: Array Object
Next: JavaScript valueOf() 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://w3resource.com/javascript/object-property-method/array-unshift.php