The push() method adds new items to the end of an array, and returns the new length.
Note: The new item(s) will be added at the end of the array.
Note: This method changes the length of the array.
Syntax and Usage
array.push(item1, item2, ..., itemX)
Parameter Values
item1, item2, ..., itemX Required. The item(s) to add to the array
Lets Start
Example(1)
1.Create Array
var flowers = ["Lily", "Rose", "Lotus", "Jasmine"];
document.getElementById("demo").innerHTML = flowers;
function addflowers() {
flowers.push("Tulip");
document.getElementById("demo").innerHTML = flowers;
}
Example(2)
<script>
var flowers = ["Lily", "Rose", "Lotus", "Jasmine"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.push("Tulip", "Orchid", "Carnation");
document.getElementById("demo").innerHTML = fruits;
}
</script>
Complete code to Push New Elements to An Array
<!DOCTYPE html>
<html>
<head>
<title>Add New Element To An Array In JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<br>
<br>
<div class="text-center">
<h1>Add New Element To An Array In JavaScript</h1>
</div>
<br>
<div class="well">
<button class="btn btn-primary" onclick="addflowers()">Click it</button>
<h1 id="demo"></h1>
</div>
<br>
</div>
</body>
</html>
<script>
var flowers = ["Lily", "Rose", "Lotus", "Jasmine"];
document.getElementById("demo").innerHTML = flowers;
function addflowers() {
flowers.push("Tulip");
document.getElementById("demo").innerHTML = flowers;
}
</script>