Add element at the beginning of javascript array

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.

<button onclick="unshiftElement()">Unshift Element</button>

<p id="demo"></p>

<script>
var courses = ["javascript", "php", "angularjs", "node js"];
document.getElementById("demo").innerHTML = courses;

function unshiftElement() {
var shifted_element = courses.unshift("Mongo DB");
console.log(shifted_element);
document.getElementById("demo").innerHTML = courses;
}
</script>

The unshift() method returns the new array length.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *