JavaScript unshift(): Add Elements to the Beginning of an Array

The JavaScript unshift() method is used when we need to add new elements at the 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 the unshift() method in JavaScript is:

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

Note: A minimum of 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

Following is another example demonstrating the "unshift()" method in JavaScript:

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 »


Liked this post? Share it!