Skip to content

JavaScript append to Array | 5 Ways With example code

  • by

JavaScript appends to array means adding an element into the existing Array. There are many ways to add new elements to a JavaScript array. Like push(), splice(), Concat(), etc methods.

5 Ways to Add new elements into Array

This 5 ways divided into 2 ways- Change and not change the original Array.

  • Change the original array
    1. Push: The simplest way to add items to the end of an array
    2. splice: Remove existing elements and/or adding new elements
    3. array.length: Use array index
  • Create a new array and the original array remains
    1. contact: merge arrays
    2. spread: Use spread to create a copy or merge two separate arrays

Examples of JavaScript append to Array

Let’s see HTML examples for it:-

push method()

<!DOCTYPE html> 
<html> 
<body> 
        <script> 
        var arr = ["A", "B", "C", "D"]; 
        arr.push("E");
        alert(arr);
        
        </script>     
</body> 
</html> 

Output:

splice Method

<!DOCTYPE html> 
<html> 
<body> 
        <script> 
        var arr = ["A", "B", "C", "D"]; 
        arr.splice(2, 1, "x", "Y"); 
        alert(arr);
        
        </script>     
</body> 
</html> 

Output: A,B,x,Y,D

array.length

<script> 
        var arr = ["A", "B", "C", "D"]; 
        arr[arr.length] = 'E';
        alert(arr);
        
        </script> 

concat method

<!DOCTYPE html> 
<html> 
<body> 
        <script> 
        var arr1 = ["A", "B", "C", "D"]; 
        var arr2 = ["x", "Y"]; 
   
        var arr = arr1.concat(arr2);

        alert(arr)

        </script>     
</body> 
</html> 

Output: A,B,C,D,x,Y

spread method

<!DOCTYPE html> 
<html> 
<body> 
        <script> 
        var arr1 = ["A", "B", "C", "D"]; 
        var arr2 = ["x", "Y"]; 
   
        var arr = [...arr1, ...arr2]

        alert(arr)

        </script>     
</body> 
</html> 

Output: A,B,C,D,x,Y

How to append something to an array?

Use push method a simplest way to add items to the end of an array.

Add a new item to an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

Do comment if you have any doubts and suggestion on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading