Append Item To Array In JavaScript


In this short article, we will learn how to append an item to an array?

In JavaScript, there are different inbuilt methods that helps us to add items in an array. In this post we will be using push() method and spread operator (...) to perform the task.

Method 1 : Using push() to Append Item in an Array.

The push() method is use to add items to the end of an given array and return a new length of array. This method modifies the original Array.

Syntax:

Array.push(item)

You can pass more then one item in push() method. Example Array.push(item1,item2,...,itemN)

Example:

const array = [1,2,3]
array.push(4)

console.log(array)

Output:

[ 1, 2, 3, 4 ]

Method 2 : Using Spread Operator to Append items in an Array

In JavaScript ES6, we get spread operator that helps us to add more then one items in a given array.

The spread operator (...) allows an iterable (like array) and expands it into individual items. This method do not modify the given array and will instead returns a new array.

Syntax:

var newArray = [...values];

Example:

const arr1 = [1,2,3]
const arr2 = [4,5,6]
const newArray = [...arr1, ...arr2]

console.log(newArray)

Output:

[ 1, 2, 3, 4, 5, 6 ] 

Related Topics:

How To Remove Object From Array In JavaScript?

Compare Elements Of Two Arrays In JavaScript

Merge Two Arrays And Remove Duplicates - JavaScript

How To Copy Or Clone An Array In JavaScript

Convert array to string with brackets and quotes in JavaScript


💾 Recommended Articles