JavaScript Append to Array
Oct 20, 2020
JavaScript arrays have a push()
method that add one or more elements to the end of an array.
const arr = ['a', 'b', 'c'];
arr.push('d');
arr; // ['a', 'b', 'c', 'd']
arr.push('e', 'f');
arr; // ['a', 'b', 'c', 'd', 'e', 'f']
Append to the Beginning
The push()
function adds a new element to the end of the array. To add elements
to the beginning, you should use the unshift()
method.
const arr = ['d', 'e', 'f'];
arr.unshift('c');
arr; // ['c', 'd', 'e', 'f']
arr.unshift('a', 'b');
arr; // ['a', 'b', 'c', 'd', 'e', 'f']
Append to Middle
To append an element to somewhere other than the beginning or end of the array,
use the splice()
method.
const arr = ['a', 'b', 'd'];
let start = 2;
let deleteCount = 0;
arr.splice(start, deleteCount, 'c');
arr; // ['a', 'b', 'c', 'd'];
Immutable Methods
Some frontend apps (often apps built with React) rely on immutability for faster comparisons of large objects.
The push()
, unshift()
, and splice()
methods modify the array in place, so
you can't use them in apps where immutability is a concern.
To add elements to the end or beginning of the array, you can use the concat()
method:
let arr = ['c'];
arr = arr.concat(['d', 'e']);
arr; // ['c', 'd', 'e']
// You can also use `concat()` to add to the beginning of
// the array, just make sure you call `concat()` on an array
// containing the elements you want to add to the beginning.
arr = ['a', 'b'].concat(arr);
arr; // ['a', 'b', 'c', 'd', 'e']
Another common pattern is using the spread operator.
let arr = ['c'];
// Append to the end:
arr = [...arr, 'd', 'e'];
arr; // ['c', 'd', 'e']
// Append to the beginning:
arr = ['a', 'b', ...arr];
arr; // ['a', 'b', 'c', 'd', 'e']
arr = ['c'];
// Append to the middle:
arr = ['a', 'b', ...arr, 'd', 'e'];
arr; // ['a', 'b', 'c', 'd', 'e']
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!