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>

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

function unshiftElement() {
var shifted_element = courses.unshift("Mongo DB");
document.getElementById("demo").innerHTML = courses;

The unshift() method returns the new array length.

Share This:

Leave a Reply

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