How to Create and Manipulate JavaScript Arrays

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

In this tutorial, you will learn how to use JavaScript arrays.

Table of Contents

You can skip to a specific section of this tutorial using the table of contents below:

What is a JavaScript Array?

A JavaScript array is a data structure used to store a list of elements where the order is maintained.

Array items can be any type of data structure within the JavaScript programming language. As a few examples, an array could contain:

  • Numbers
  • Objects
  • Functions
  • Strings
  • More arrays (these are called nested arrays)

Here are a few other pieces of array terminology that you should be aware of before proceeding:

  • If you're using strict terminology, every element within an array is called an item (although people will know what you mean if you say element)
  • The location of an item within an array is called its index
  • The number of items within an array is called the length of the array

How to Create Your First JavaScript Array

You can create your first JavaScript array in a similar fashion to creating the other data structures that we've explored in this course. Specifically, you can use the const, let, or var keywords followed by a variable name and the = assignment operator.

After the = operator, you need to specify the array's items inside of square brackets. As an example, here is how you could create an array called integers that contains the first 4 non-zero integers:

const integers = [1, 2, 3, 4];

As you can see, the syntax for creating an array is fairly simple. The items are separated by commas and all the items are wrapped in square brackets.

As mentioned, arrays do not need to specifically contain numbers. They can contain other data structures too.

Here is another example of a JavaScript array that contains only strings (instead of only numbers, as before):

const names = ['Nick', 'McCullum'];

How to Access Items From Within an Array

Just as we used square brackets to create our arrays earlier, we can also use square brackets to access items within an array. To do this, we simply need to pass the variable name and the item's index into console.log().

const integers = [1, 2, 3, 4];

const names = ['Nick', 'McCullum'];

console.log(integers[0]);

//Logs 1 to the console

console.log(names[1]);

//Logs 'McCullum' to the console

Note that since JavaScript is a zero-indexed programming language, then the first item of an array will have index 0, the second item of an array will have index 1, and so on.

How to Determine the Length of an Array

The length of an array is equal to the number of items that the array contains.

The arrays that we have worked with so far have been small enough that we can easily determine their length using the eyeball test. It's obvious as first glance that integers contains 4 items and names contains 2 items:

const integers = [1, 2, 3, 4];

const names = ['Nick', 'McCullum'];

When working with larger arrays, however, it's not so easy to determine their length.

JavaScript arrays contain a built-in attribute called length that solves this problem by allowing us to easily determine the length of the array. For example, here's how you could calculate the length of the integers and names arrays:

integers.length;

//Returns 4

names.length;

//Returns 2

How to Access the Last Item of a JavaScript Array

Accessing the first item of an array is easy - you can simply pass in the index 0 into the square brackets. On the other hand, there are a number of situations in which you'll want to access the last item of a JavaScript array, whose index is likely unknown (especially for large arrays).

Many languages allow you to pass in an index of -1 to access the last item of an array. For example, Python lists support this functionality. However, JavaScript does not. Passing in an index of -1 returns undefined.

What is the solution?

The last item of a JavaScript array will have an index that is 1 less than the length of the array. Because of this, the easiest way to access the last item of a JavaScript array is to pass in an index of array.length - 1.

Here are two examples of how you could use this strategy to access the last item of our integers and names arrays:

integers[integers.length-1];

//Returns 4

names[names.length-1];

//Returns McCullum

Important JavaScript Array Methods

The JavaScript array data type contains a number of built-in methods that you can use to create functionality within your code. We will explore several of the most important JavaScript array methods throughout the rest of this tutorial.

Before digging in, let's discuss mutable vs. immutable JavaScript methods, which are the two broad categories that every method fits into. Here is the main difference:

  • Mutable array methods perform some sort of mutation to the array. Said differently, the array will be fundamentally different after the method is run.
  • Immutable array methods do not change the original array, but they do return a different array that has been modified in some way.

If this is not completely clear, do not worry - we will see many examples in the rest of this tutorial.

How to Add Items to an Array Using the push and unshift Methods

JavaScript arrays come with a built-in method called push that allow us to easily add items to the end of an array. The push method takes a single argument - the item that is to be added to the array.

Here is how we could use the JavaScript push method to add 5 to the end of our integers method:

integers.push(5);

console.log(integers);

//Logs [1, 2, 3, 4, 5] to the console

Since the purpose of the push method is to add items to the end of an existing array, then it goes without saying that push is a mutable array method.

The unshift method is a close contemporary of the push method but instead of adding the item to the end of the array, it adds it to the beginning of the array.

Here's how you could use the unshift method to add 0 to the start of our recently-modified integers array:

integers.unshift(0);

console.log(integers);

//Logs [0, 1, 2, 3, 4, 5] to the console

As with push, since the purpose of the unshift method is to add items to the start of an existing array, then it goes without saying that unshift is a mutable array method.

The JavaScript reverse Array Method

The reverse method is a mutable JavaScript array method that reverses the indexes of items within a JavaScript array.

Here is an example of how we could use the reverse method to reverse the order of the items with our names array:

const reversedNames = names.reverse()

If you log this new reversedNames variable to the console, here is what it prints:

["McCullum", "Nick"]

Note that since the reverse method is a mutable array method, then the original names array has also been altered:

console.log(names);

//Logs ["McCullum", "Nick"] to the console

The JavaScript slice Array Method

JavaScript's slice array method is an immutable method that allows you to take a portion of an existing array and assign it to a new array. The slice method takes two arguments:

  • begin: the first index of the new array
  • end: the last index of the new array. Note that the item at this index is not included in the new array.

To see the slice method in action, let's use our integers array from earlier in this tutorial.

const middleIntegers = integers.slice(1,3);

console.log(middleIntegers);

//Returns [2, 3]

Note that since the slice method is immutable, the original integers array remains unchanged.

The JavaScript splice Method

The JavaScript splice method's functionality is almost identical to the functionality of the JavaScript slice method. The only two differences are:

  1. The splice method is mutable - which means that it actually modifies the value of the array that it is performed on.
  2. Instead of taking end as its second argument, it takes count - which is the number of items of the original array that you'd like to splice from the array.

The slice and splice methods are similar enough that splice does not require any further explanation.

Fair warning, though - the similarity of these methods is bound to introduce bugs in your code at some point, and being aware of how they're related is very useful for debugging purposes.

How to Add an Item to the Middle of a JavaScript Array

Unfortunately, there is no built-in method that allows us to easily add an item to the middle of a JavaScript array. Instead, we need to get creative with the ... operator (pronounced as the spread operator) along with the slice method.

To see this in action, let's again consider our integers array:

const integers = [1, 2, 3, 4];

Here's how you would add the item 2.5 between the item 2 and the item 3:

const integersAndDecimals = [	...integers.slice(0, 2),
				
				2.5,

				...integers.slice(2)

				];

console.log(integersAndDecimals);

//Logs [1, 2, 2.5, 3, 4] to the console

How to Remove an Item from the Middle of a JavaScript Array

Just like there is no good built-in method for adding an item to the middle of a JavaScript array, there also isn't a solution for removing items from the middle of an array.

Fortunately, we can again combine the spread operator with the slice method to build a workaround. Here's how we would remove the item 2.5 from the following array:

const halfSteps = [1, 1.5, 2, 2.5, 3, 3.5];

const halfSteps2 = [

			...halfSteps.slice(0,3),

			...halfSteps.slice(4)

			];

console.log(halfSteps2);

//Logs [1, 1.5, 2, 3, 3.5] to the console

How to Prevent Mutable Array Methods From Mutating Your Arrays

There are certain situations in which you might want to use a mutable array method, but want to avoid having the mutation applied to your original array.

Fortunately, there is a workaround. To avoid the mtuation, you simply need to create a copy of the original array.

The easiest way to do this is by using the ... operator, often called the spread operator. Here's how we could use this operator to take a copy of the integers array and then apply the reverse method to the copied array:

const integers = [1, 2, 3, 4];

const integersCopy = [...integers];

const integersCopyReverse = integersCopy.reverse();

console.log(integers);

//Logs [1, 2, 3, 4] to the console

console.log(integersCopy);

//Logs [4, 3, 2, 1] to the console

console.log(integersCopyReverse);

//Logs [4, 3, 2, 1] to the console

Notice that while the integersCopy and integersCopyReverse variables have both been reversed, the original integers variable remains unchanged.

Note that this could also be done in one line, like this:

const integers = [1, 2, 3, 4];

const integersReversed = [...integers].reverse();

This version is arguably more readable, but seeing multiple steps can be helpful for education's sake.

Final Thoughts

In this tutorial, you learned how to create and manipulate JavaScript arrays.

Here is a brief summary of what you learned:

  • What a JavaScript array is
  • The syntax required to create your first JavaScript array
  • How to access specific items from within a JavaScript array by passing their index into square brackets
  • How to determine the length of a JavaScript array by accessing the length attribute via the dot operator
  • How to access the last element of an array by using the index array.length - 1
  • How to add items to a JavaScript array using the push and unshift methods
  • How to use the reverse, slice, and splice methods in JavaScript
  • How to add and remove items from the middle of a JavaScript array
  • How to prevent mutable JavaScript methods from modifying a JavaScript array