JavaScript – Add Element to Beginning of Array

To add an element to the beginning of an array in JavaScript, call unshift() method on this array and pass the element as argument. unshift() method modifies the original array, and returns the length of the modified array.

The syntax to add an element e to the beginning of an array arr is

</>
Copy
arr.unshift(e)

Example

In the following example, we have taken an array in arr. We add an element 'mango' to the beginning of this array arr using unshift() method.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry'];
        var e = 'mango';
        arr.unshift(e);
        document.getElementById('output').innerHTML = 'Array : ' + arr;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to add an element to the beginning of an array using unshift() method.