How to append something to an array?

append, arrays, javascript

Solution

Use the `Array.prototype.push` method to append values to the end of an array:

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

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

console.log(arr);

You can use the `push()` function to append more than one value to an array in a single call:

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

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Note that the `push()` method returns the updated length of the array.

Update

If you want to add the items of one array to another array, you can use `firstArray.concat(secondArray)`:

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

// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

Update

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use `Array.prototype.unshift` for this purpose.

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

It also supports appending multiple values at once just like `push`.

Update

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended or prepended, compliant with the spirit of functional programming.

const arr = [
  "Hi",
  "Hello",
  "Bonjour",
];

const newArr1 = [
  ...arr,
  "Salut",
];
const newArr2 = [
  "Salut",
  ...arr,
];

console.log(newArr1, newArr2);

Problem

How do I append an object (such as a string or number) to an array in JavaScript?

Original source