JavaScript array add to front | Example code

Use .unshift() to add elements into front of JavaScript array. The unshift method modifies the existing array by adding the arguments to the beginning. It Most efficient way to prepend a value to an array in JS.

Example of JavaScript array add to the front

Let’s Add new items to the beginning of an array in JavaScript.

Note: This way will changes the length of an array.

<!DOCTYPE html>
<html>

<body>
    <script type="text/javascript">
        var alpha = ["A", "O", "C", "D"];
        alpha.unshift("E","B");
        alert(alpha);
    </script>

</body>
</html>

Output:

JavaScript array add to front

Q: How to add new items at the end of an array in JavaScript?

Answer: Use the push() method to add element in the last of JS array.

Read More:- JavaScript array push | method | Add an ele​men​t to the array

FYI:-

  • unshift/push – add an element to the beginning/end of an array
  • shift/pop – remove and return the first/last element of an array

Do comment if you know another way or example. You can post your questions and doubts also.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.