Javascript

How to append an item into an Array in Javascript

There are many ways by which you can append an item into an Array in Javascript. In this article, we are going to talk about all those different methods by which you can easily append anything into an Array in Javascript.

Also Read: Javascript Interview Questions

Javascript Append to Array

Array.push() method to append values to an array in Javascript

Array.push() method can be used to append both single and multiple values into an array. Below are the methods showing how to append single and multiple values in Javascript Array.

Append Single value to Array in Javascript

You can easily append values into an array using the Javascript Array.push() method. The push() method adds new items to the end of an array and returns the new length. This property of Array.push() method helps us to append anything into an array in Javascript. Here is an example of the same.

// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);
[
  "Hi",
  "Hello",
  "Bonjour",
  "Hola"
]

Append Single value to Array in Javascript

It must be noted that using the same Array.push() method, you can also append multiple values into an array at the same time. To append multiple items to an array, you can use push() by calling it with multiple arguments. Here is an example showing this in code.

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')

Array.concat() method to append values to an Array in Javascript

If there is a case where you want to add the items of one array to another array, you can use Array.concat() method. In this way, you are appending a whole array into the original array. here is an example showing this in code.

var arr = [
  "apple",
  "banana",
  "cherry"
];

arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

Array.unshift() method to append any value to the start of an array in Javascript

If you want to append an item or value into the start of an array, then you can use the Array.unshift() method. The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);

So, this is all about appending an item or value into an array in Javascript. Thanks for Reading!

Leave a Comment