JavaScript Array unshift() method : The unshift() method is used to add new item at the first position of an array. The unshift() method will return the new length of an array. The unshift() method will change the length of the array.
Syntax of the unshift() method :
array.unshift()
Example of Array unshift() method : Here I will show you how to add new element at the beginning of the array.
<!DOCTYPE html>
<html>
<body>
<p>To add new element at starting of the array, click the button "add new element".</p>
<button onclick="addElement()">add new element</button>
<p id="container"></p>
<script>
var students = ["Rajesh", "Pankaj", "Sumit", "Manish", "Pramod"];
document.getElementById("container").innerHTML = students;
function addElement() {
students.unshift("Ashok", "Nitin Kumar");
document.getElementById("container").innerHTML = students;
}
</script>
</body>
</html>
Output :
Ashok, Nitin Kumar, Rajesh, Pankaj, Sumit, Manish, Pramod
0 Comment(s)