Last Updated On By Anmol Lohana
Unshift is a built-in JavaScript Function of array. Unshift JavaScript adds one or more items in the array of elements at the beginning and returns a new array. Unshift JavaScript method will change the length of an array according to the number of values we added in an array using the Method Unshift JavaScript Array . Browsers that support Unshift JavaScript Array method are Chrome 1.0, Internet Explorer or Edge 5.5, Firefox Mozilla 1.0, Safari, and Opera. Unshift JavaScript Array Method will return undefined in Internet Explorer or Edge 8 and above versions.
Table of Contents
array.unshift(item_1, item_2,…item_n)
Unshift JavaScript method takes only one single item as a parameter. These array items are to be added at the beginning of the array. After inserting the values at the beginning of the array, this method will return a new length array. Let’s have a look at some examples:
In the example, we are going to create an array of names. We will print the array’s length before invoking the unshift JavaScript method and then print the values of the original array. After that, we will invoke the unshift() method on the created array. Then we will print the length of the array after invoking the unshift() method and then print the updated array.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unshift Method</title>
</head>
<body>
<script>
var array=["AL","MM", "BS"];
document.writeln("Length before invoking unshift(): "+array.length+"<br>");
document.writeln("Original array: "+array+"<br>");
array.unshift("MB","PK");
document.writeln("Length after invoking unshift(): "+array.length+"<br>");
document.writeln("Updated array: "+array);
</script>
</body>
</html>
In the example, we are going to create objects of names to add to the array. We will print the array’s length before invoking the unshift() method and then print the values of the original array. After that, we will invoke the unshift() method on the created array-like object. Then we will print the length of the array after invoking the unshift() method and then print the updated array.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unshift Method</title>
</head>
<body>
<script>
const objA = {
name: 'AA'
}
const objB = {
name: 'BS'
}
const objC = {
name: 'MB'
}
let array = [objA.name, objB.name];
document.writeln("Length before invoking unshift: "+array.length+"<br>");
document.writeln("Original array: "+array+"<br>");
array.unshift(objC.name);
document.writeln("Length after invoking unshift: "+array.length+"<br>");
document.writeln("Updated array: "+array);
</script>
</body>
</html>
In conclusion, we discussed unshift() array method of JavaScript. We saw its definition with syntax and browser support. It is an in-built JavaScript Method. Also, we performed two examples to understand the unshift method better.
You can go for JavaScript shift() Method also.