JavaScript Arrays: Everything You Need To Know

JavaScript Arrays: Everything You Need To Know

First Written

Last Updated

Let’s say you’re working in Javascript and you want to store a collection of data, but you’re not sure what data structure is the right one to use.

You have one key question: does my data have a natural order? Or, put another way, does it matter if one data element is stored or presented before another?

If not, a JavaScript object - or hashmap - is likely the right tool for you, and this article won’t help much.

But if the order of your data matters, a JavaScript array is your best bet, and this article will tell you everything you need to know about using them.

We’ll start by describing how you can create a JavaScript array and go through some common use cases of arrays. Then we’ll give an overview of some advanced concepts, like comparing the equality of two arrays, and wrap up by walking through the various built-in methods and properties that can be used with JavaScript arrays.

Creating JavaScript Arrays

So you’ve decided you want to use an array. Now what?

Well, you have two ways of creating a JavaScript array:

  • using an array literal
  • using the Array constructor

Let’s go through some examples to show what we mean.

To create a JavaScript array using an array literal, we just have to declare a new variable name and set it equal to an empty array like so:

And that’s it; we now have an array stored in a variable called newEmptyArray.

So, that’s how we create an empty array. But what if we don’t want our array to be empty? If we create an array using an array literal, we could also create an array with data in it.

Let’s take a look at an example:

Above, we’ve declared a new array with the variable name newArrayWithThreeElements and we’ve initialized it to have three strings inside of it: “hamburger” as the first element, “pizza” as the second element, and “salad” as the third element.

So that’s how we can use array literals to create a JavaScript array. Let’s move onto the second way of creating JavaScript arrays: by using the Array constructor. Here’s an example of how it works:

And that’s it. Pretty simple, huh? After this line has been executed, you have a new variable called newArrayUsingConstructor, which stores an empty array. There’s no difference between this array and the array created with an array literal.

At this point, you might wonder if it’s possible to create an array that isn't empty using the Array constructor. And yes, yes, you can. You can create a new non-empty array using the Array constructor like so:

And after this line has been executed, the variable newNonEmptyArrayFromConstructor has been created and initialized to store three strings inside of it, exactly like the previous newArrayWithThreeElements example above.

And that’s what you need to know about creating JavaScript arrays. There are more advanced tricks (see what happens if you pass the array constructor a singular number instead of multiple elements,) but you can safely ignore those as you’re getting started.

Now that you know how to create JavaScript arrays let’s explore how to access what a JavaScript array has stored inside it.

Accessing JavaScript Array Elements

Accessing elements in a JavaScript array is pretty important. Otherwise, what’s the point of storing data in an array if you can’t see what’s in it? Well, there are three ways of accessing data in a JavaScript array:

  • Accessing an element by its index in the array
  • Accessing (and removing) the last element in an array with the pop method
  • Accessing (and removing) the first element in an array with the unshift method

Let’s go through these one-by-one, starting with accessing an element by its index.

A quick reminder of what an index is: an index is the order position of a piece of data within an array.

And one slightly quirky thing about array indices is that the first index or an array isn’t 1, but is instead 0.

So accessing the first element of an array would look like this:

Let’s breakdown what’s happening here, starting with newArrayWithThreeElements, which you might remember from the example above.

This slightly-long term is the variable name for an array with three elements. We’re using it here to specify which array we want to access elements of.

But what is the [0] doing after the variable name?

When used immediately after an array, [index] can be used to specify which element in the array you want to access, where index is any number. So the above line is how we can access the string “hamburger”. We can save it to a variable like so:

And if we wanted to save the second element to a variable we could do that, too:

Or the third:

But what if we try to access an element that isn’t populated? Since the element is empty, the value we access will be undefined:

And that’s how you can access array elements using their index. Let’s move on to how you can use some built-in array methods to access and remove elements from either end of an array.

We’ll start with the pop method.

Any JavaScript array had a .pop() method that can be used to remove the last element from an array and return the element. Here’s an example:

This has done two things:

  • Save the last element (the string “salad”) in a variable.
  • Remove the last element from the array.

Similar to the pop method, the built-in unshift method removes and returns the first element of an array.

And those are three ways to access single elements in a JavaScript array. Let’s now explore another common use case with JavaScript arrays: how to iterate through all array elements.

Iterate Through JavaScript Array

One of the most common situations people run into with JavaScript arrays is wanting to go through all elements in them, also known as “iterating” through the array.

JavaScript has two general ways of iterating through arrays and many more specialized ways of iterating through arrays.

Let’s kick things off with the two general ways of iterating through arrays:

  • Looping through a JavaScript array
  • Iterating using arrays’ built-in forEach method

And we’ll get to the more-specialized ways of iterating through JavaScript arrays in the “JavaScript Array Methods” section below.

Looping Through a JavaScript Array

Loops are a common way to iterate through JavaScript arrays.

Here is how we could use a for loop to iterate through a JavaScript array:

I’ll hold off on diving into the nuances of for loop syntax here, but in plain English the outer part of the for loop is roughly saying “execute the inner part of this for loop once for every element in the array.”

You can modify the top line of the for loop to change the behavior of the for loop, but - in my experience - this outer loop syntax is what you’ll see the majority of the time you run into for loops.

This isn’t the only way we can iterate through JavaScript arrays, though. The built-in forEach method is used much more often in modern applications. Let’s take a look.

Iterating Using the forEach Method

As we’ll explore further in this guide, JavaScript arrays have many built-in methods. And one of the most commonly used methods is the .forEach method, which can be used to iterate through all elements of an array like so:

This code block has two steps:

  1. It declares an array with three number elements, setting it to the variable name“arrayOfNumbers.
  2. It iterates through all elements of the array and logs the element its corresponding index.

It might be a bit confusing if this is the first time you’ve encountered higher-order functions (and I recommend reading up on them if so,) but otherwise, it should be pretty straightforward.

Mutating JavaScript Arrays

One thing that’s tricky about arrays in JavaScript is that the values in them can be changed (or “mutated”) even if declared an array with the const keyword, which will keep you from mutating a string or number variable.

If this is news to you, just know that you need to be careful with how array elements are changed over time. It’s really easy to end up in a situation where two separate parts of your program change the same array, leading to some strange errors.

If you’re interested in learning more about why this is the case, I recommend reading up on the concept of “pass by reference.” This will dive a bit deeper into how JavaScript works, though you can safely put this reading off for a while if you’re just getting started.

Checking Equality Between Arrays

Checking if two arrays are “the same” is a bit trickier in JavaScript than it is for checking whether two strings or numbers are the same.

For example, here’s how we can check if two strings are the same:

But if we were to do the same thing with two arrays that have the same elements, it wouldn’t work how we might expect:

Why this is the case gets into the notion of “pass by reference” that’s mentioned in the previous section, so we’ll refrain from diving into it here.

But if you run into the need to see if two JavaScript arrays contain the same elements, you aren’t out of luck – you have a couple of options:

  • Check whether the arrays have the same values and contain the same length
  • Use the “lodash” library’s isEqual method
  • Use JSON.stringify() to compare values (not recommended for all cases)

We aren’t going to dive into the details of the different strategies here, but I recommend reading up on their pros and cons if you find yourself in need of comparing two arrays.

JavaScript Functions