JavaScript unshift() | Add Elements to Beginning of an Array

The JavaScript unshift() method is used when we need to add new elements at beginning of an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const myArray = ["Boston", "Austin", "Denver", "Berlin"];

      myArray.unshift("Seattle", "Oakland");
      document.getElementById("xyz").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

JavaScript unshift() Syntax

The syntax of unshift() method in JavaScript is:

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

Note - Minimum one element is required.

Note - The unshift() method returns a number that equals the new length of the array after adding the specified elements to the specified array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const arr = ["Boston", "Austin", "Denver", "Berlin"];
      document.getElementById("xyz").innerHTML = arr.unshift("Seattle", "Oakland");
   </script>
   
</body>
</html>
Output

JavaScript unshift() Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Original Array: <b><span id="one"></span></b></p>
   <p>Modified Array: <b><span id="two"></span></b></p>

   <script>
      const x = ["Boston", "Austin", "Denver", "Berlin"];
      document.getElementById("one").innerHTML = x;
      x.unshift("Seattle", "Oakland");
      document.getElementById("two").innerHTML = x;
   </script>
   
</body>
</html>
Output

Original Array:

Modified Array:

JavaScript Online Test


« Previous Tutorial Next Tutorial »