Array Append In JavaScript

JavaScript provides the array type in order to store multiple items in a single object and iterate them easily. The Array is very similar to the other programming languages’ list type. We can add a new item to the arrays by using different methods in JavaScript. In this tutorial we examine push(), concat(), unshift(), spread syntax, and index number methods to add and append new items to the array.

Append with Array push() Method

An array object provides the push() method natively to append new items or items into this array. The item is provided into the push() method as a parameter and the push() method is called by the array object. In the following example, we append a new item into the array named names.

var names = ["İsmail","Ahmet"];

names.push("Ali");

console.log(names);

Append Array Into Another Array with concat() Method

Another method to append an array is the concat() method. The concat() method can be used to an item or an array into another array. An array should be provided in the concat() method. The array can be a single or multi-item.

var names = ["İsmail","Ahmet"];

names.push(["Ali"]);

console.log(names);

Append Start of the Array with unshift() Method

By default appended items or items are added to the end of the array. The unshift() method can be used to append items to the start of the array. The item is provided as a parameter to the unshift() method.

var names = ["İsmail","Ahmet"];

names.unshift("Ali");

console.log(names);

Append Array with Spread Syntax

The new version of JavaScript ES6 provides the spread syntax order to spread existing arrays into another array. The first array is spread into another array using the ... operator before the array name. In the following example, we spread the array names into the array new_names.

var names = ["İsmail","Ahmet"];

var new_names = [...names,"Ali"]

console.log(new_names)

Append with Index Number

The JavaScript array provides the ability to set an item by providing its index number. We can use the array length as the index number for the new item and set its value.

var names = ["İsmail","Ahmet"];

names[names.length]="Ali"

console.log(new_names)

Leave a Comment