2 Example(s) of JavaScript push function


Description :

JavaScript push function is used to add an item at the end to array. We have an array with four element a,b,c and d. arr.push("e","f") will add e and f at the end of array. See the code snippet:


JavaScript push function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="addElement()">Add new element</button>
<p id="sample"></p>
<script>
var arr= ['a', 'b','c','d'];
document.getElementById("sample").innerHTML = arr;
function addElement() {
    arr.push("e","f");
    document.getElementById("sample").innerHTML = arr;
}
</script>

</body>
</html>

Output

Description :

In this example, We have an array of vegetables and JavaScript push function add "tomato" vegetable at the end of array. See the code snippet:


JavaScript push function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>

<button onclick="addElement()">Add new element</button>
<p id="sample"></p>
<script>
var veg = ["beans", "mushroom", "potato", "brinjal"];
document.getElementById("sample").innerHTML = veg ;

function addElement() {
    veg.push("tomato");
    document.getElementById("sample").innerHTML = veg ;
}
</script>

</body>
</html>

Output