Skip to content

JavaScript Array unshift() | Method

  • by

Using the JavaScript unshift() method you can add one or more elements to the beginning of a given array. This method overwrites the original array and returns the new length of the array.

array.unshift(item1, item2, ..., itemX)
  • array: The array to which you want to add elements at the beginning.
  • item1, item2, ..., itemN: One or more items or values that you want to add to the beginning of the array. You can specify multiple items separated by commas.

JavaScript array unshift

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    const array1 = [1, 2, 3];

    console.log(array1.unshift(4, 5));
    console.log(array1.unshift(6));

    console.log(array1);
  </script>
</body>
</html> 

Output:

JavaScript Array unshift method

More examples

var languages = ["JavaScript", "Python", "Java", "Lua"];

var count = languages.unshift("C++");
console.log(languages); // [ 'C++', 'JavaScript', 'Python', 'Java', 'Lua' ]
console.log(count); // 5

Do comment if you have any doubts or suggestions on this Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading