Appending and Prepending Items to an Array

Hero image for Appending and Prepending Items to an Array. Image by Marcel Strauß.
Hero image for 'Appending and Prepending Items to an Array.' Image by Marcel Strauß.

This Article is Over Ten Years Old...

Things can and do move very quickly in tech, which means that tech-related articles go out of date almost as soon as they have been written and published. If you are looking for up-to-date technical advice or opinion, it is unlikely that you will find it on this page.

You may find that my recent articles are more relevant, and you are always welcome to drop me a line if you have a specific technical problem you are trying to solve.

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));//=> 6

The Wrap‑Up

Appending and prepending items to a JavaScript array is a very common task in frontend development and can be achieved very simply using the push() and unshift() methods, rather than manually manipulating the array yourself.


Categories:

  1. Adaptive Development
  2. Front‑End Development
  3. JavaScript
  4. Responsive Development