Home »
JavaScript
Array unshift() method with example in JavaScript
JavaScript unshift() method: Here, we are going to learn about the unshift() method of array in JavaScript.
Submitted by IncludeHelp, on February 28, 2019
JavaScript unshift() method
unshift() method is used to add/insert one or more elements at the beginning of an array. And it returns a new length of the array.
Syntax
array_name.unshift(element1, element2, ...);
Parameters
Elements to be added, one element in required others are optional.
Return value
new length of the array.
Sample Input/Output
Input:
var arr1 = [10, 20, 30, 40, 50];
Function call:
arr1.unshift(111);
arr1.unshift(100,200);
Output:
100,200,111,10,20,30,40,50
JavaScript Code to demonstrate example of Array.unshift() method
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var arr1 = [10, 20, 30, 40, 50];
var arr2 = ["Amit", "Ankur", "Akash"];
//printing arrays before the insering elements
document.write("arr1: " + arr1 + "<br>");
document.write("arr1 length: " + arr1.length + "<br>");
document.write("arr2: " + arr2 + "<br>");
document.write("arr2 length: " + arr2.length + "<br>");
//adding elements
var len1 = arr1.unshift(100,200);
var len2 = arr2.unshift("Aman");
document.write("<br>After inserting...<br><br>");
document.write("arr1: " + arr1 + "<br>");
document.write("new arr1 length: " + len1 + "<br>");
document.write("arr2: " + arr2 + "<br>");
document.write("new arr2 length: " + len2 + "<br>");
</script>
</body>
</html>
Output
arr1: 10,20,30,40,50
arr1 length: 5
arr2: Amit,Ankur,Akash
arr2 length: 3
After inserting...
arr1: 100,200,10,20,30,40,50
new arr1 length: 7
arr2: Aman,Amit,Ankur,Akash
new arr2 length: 4
JavaScript Array Object Methods »