How to Add Elements Into an Array in JavaScript?

Aug 29, 2022 . Admin



Hello dev,

This tutorial shows you how to add elements from an array in javascript. We will look at examples of how to add elements into an array in javascript. Here you will learn to add elements in an array using javascript. it's a simple example of javascript add element in the array.

The first and probably the most common JavaScript array method you will encounter is push(). The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Add Element into an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Add Element into an Array in Javascript? -  MyWebtuts.com</h1>
        
        <p id="item" ></p>
        <script type="text/javascript">
            const fruits = ["kiwi","graps","apple","orange"]; 
            fruits.push("mango");

            //write text to <p> tag
            document.getElementById("item").innerHTML = fruits;
        </script>
    </body>
<html>
Output:
kiwi,graps,apple,orange,mango
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Add Element from Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Add Element from Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const animals = ["cat","cow","pigs","goats"]; 
            fruits.push("dog");

            //give output to console
            console.log(animals);
        </script>
    </body>
<html>
Output:
Array ["cat", "cow", "pigs", "goats", "dog"]
I hope it will help you...
#Javascript