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
- Push: The simplest way to add items to the end of an array
- splice: Remove existing elements and/or adding new elements
- array.length: Use array index
- Create a new array and the original array remains
- contact: merge arrays
- 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