• JavaScript Video Tutorials

JavaScript - Array unshift() Method



In JavaScript, the Array.unshift() method is used to add one or more elements to the start of an array and returns the new length of the array. This method overwrites the existing array.

To make the room for the new elements, it modifies the array by shifting the existing elements to the next (higher) index. For instance, if we consider an array arr = [1, 2, 3]; if we add arr.unshift(11,22); then the result will be [11,22,1,2,3].

Syntax

Following is the syntax of JavaScript Array unshift() method −

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

Parameters

This method accepts one parameter. The same is described below −

The "element1…element" are the elements that will be added to the beginning of the array.

Return value

This method adds one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.

Examples

Example 1

In the following example, we are using the JavaScript Array unshift() method to add new elements at the beginning of the array.

<html>
<body>
   <p id="demo1"></p>
   <p id="demo2"></p>
   <script>
      const animals = ["Tiger", "Elephant", "Dinosaur"];
      animals.unshift("Lion", "Cheetah");
      document.getElementById("demo1").innerHTML = animals;
      document.getElementById("demo2").innerHTML = animals.length;
   </script>
</body>
</html>

After executing the above program, new elements are added to the beginning of the array. Additionally, the length of the array changes from 3 to 5.

Output

Lion,Cheetah,Tiger,Elephant,Dinosaur

5

Example 2

If we do not pass any elements to the unshift() method, the elements and length of the array remains same.

<html>
<body>
   <p id="demo1"></p>
   <p id="demo2"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
      animals.unshift();
      document.getElementById("demo").innerHTML = animals;
   </script>
</body>
</html>

The length and elements in the array remains the same.

Example 3

Here, the sub-array [1, 4] is treated as a single element, and it is added at the beginning of the animals array. As a result, the array's length becomes 6.

<html>
<body>
   <p id="demo1"></p>
   <p id="demo2"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
      animals.unshift([1, 4]);
      document.getElementById("demo1").innerHTML = animals;
      document.getElementById("demo2").innerHTML = animals.length;
   </script>
</body>
</html>

Output

As we can see in the output, the element has been added to the beginning of the array, and the length has been overwritten to 6.

1,4,Lion,Cheetah,Tiger,Elephant,Dinosaur

6
Advertisements