How To Push New Elements to An Array In JavaScript

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

JavaScript is a high-level programming language that conforms to the ECMAScript specification.Java Script can combine with any other language ( Its used as a part of web pages), whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities. In The JavaScript we have so many in built method so today we are going to discuss how to push new elements to an array

How To Push New Elements to An Array In JavaScript

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"];


2.Now Impelement code to insert new element to an array
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>

 

Related Post