Appending and Prepending Items to an Array

JavaScript arrays are a useful data structure for storing and manipulating collections of values. Arrays in JavaScript are dynamic, meaning that they can be resized and their contents can be changed during runtime.
It is really common to find yourself manipulating array data, by adding new elements to either the start or the end of an existing array. There are two primary methods available in JavaScript for doing this: push() and unshift(). These methods allow you to append elements to the end of an array or prepend elements to the beginning of an array, respectively.
Append using the push() Method
The push() method adds one or more elements (appends data) to the end of an array and returns the new length of the array.
For example, to append three additional items (4, 5, and 6) to the array [1, 2, 3] would look something like this:
let array = [1, 2, 3];array.push(4, 5, 6);console.log(array);//=> [1, 2, 3, 4, 5, 6]Of course, this doesn't just have to work with numbers within an array, any data type that can be held in an array can be appended to an existing array:
let pets = ['dog', 'cat', 'gerbil'];pets.push('goldfish');console.log(pets);//=> ['dog', 'cat', 'gerbil', 'goldfish']Prepend with the unshift() method
The unshift() method works in exactly the same way but adds one or more elements to the beginning of an array rather than the end:
let array = [1, 2, 3];array.push(4, 5, 6);console.log(array);//=> [4, 5, 6, 1, 2, 3]The Return
A brief gotcha, which I've seen more than one developer trip over in the past: if called directly, the unshift() and push() methods don't return the updated array itself, but rather they return a number that represents the length of the array after the elements have been added.
For example:
let array = [1, 2, 3];console.log(array.push(4, 5, 6));//=> 6The Wrap‑Up
Appending and prepending items to a JavaScript array is a very common task in front‑end development and can be achieved very simply using the push() and unshift() methods, rather than manually manipulating the array yourself.