JavaScript Tutorial: Array Definitive Guide

JavaScript Array Tutorial

Share This Post

As we saw, you can do a lot with variables in JavaScript. However, you can’t do everything. In fact, with a simple variable, you can represent only one piece of data. Arrays change the picture completely, and that’s why they are crucial for any developer. In this JavaScript tutorial, we will see everything you need to know about arrays.

As you guessed by now, in this javascript tutorial we will focus exclusively on arrays. This means you should already grasp the basics of JavaScript. If you don’t, the place to start is this Getting Started with JS tutorial.

Understand Arrays in JS

Array vs. Simple Variable

An array is just a special type of variable. Or, rather than special, it is a complex type. We say complex because it can hold multiple values at the same time, even heterogeneous (different in type from one another).

In fact, the main limitation we had with variables is that they can hold a single value at a time. True, we can change the content of the variable as we execute the code, but we can only put one value inside the variable at a time. This has a clear result: we need to know in advance how many variables we are going to need.

This is not particularly good when the amount of data changes depending on the user. Suppose we are working on a list of items, where each item is a string, and we want to let the user add or remove items from it. We need to know in advance how many items the user wants on the list so that we can create enough variables accordingly. That’s clearly a waste of time, and that’s where arrays come to help.

Indeed, an array is a variable that can hold multiple values at the same time. If a variable was a box, an array is an array of boxes, a sequence of boxes. Each box in the sequence works much like a variable: it can have a value in it, much like a variable.

JavaScript Array definitive guide: Array are different from simple variables because they are a set of values, not just a value
An array is a set of values, a variable is just one value.

And here we go, we can elegantly represent our list of items of our user with an array.

Size of Arrays in JavaScript

How many boxes can you have in the sequence? As many or as little as you want. In fact, you can have an array with zero boxes or an array with thousands of boxes. And, even better, the value each box has in it is completely unrelated from the ones in the other boxes. The first box can contain a string, the second a bool, the third an integer, and so on.

But things get even better. In fact, the size of the array is dynamic. You can start with an empty array (with no boxes in it), and then dynamically add boxes, thus increasing its size. And, you can also shrink it, removing elements from it, even returning to a size of zero.

You can even get or set the value of each box individually, without modifying the entire array. This is because the boxes in an array are always in sequence, so you can get or modify the value of the n-th box (e.g. the fifth box).

For obvious reasons, the size will never be negative as you can always have zero elements or more in an array, never less than zero.

Array Jargon

Hopefully, by now you are grasping the concept of an array is a sequence of boxes. However, that’s not how we call it formally, and it is important to understand the “official” jargon so that you can navigate all the information you can find on the Internet.

Each “box” of the array is an element. As we saw, each element can have its own value independent from the other elements in the array.

Elements will always appear in sequence (not in an order based on their value, it just means that the “boxes” are next to each other). As such, each element can be identified by an index. The index is the position of the element in the array, and it starts from zero. So, the very first element of the array will be element 0, the second element 1, the third element 2 and so on. We will see that we can use the index to read or update the value of a specific element in the array.

The number of elements in an array is its length (also known as size). Since the index starts from zero, the index of the last item in the array will always be length - 1. For example, if the length is 5 the index of the last item will be 4. An array that has a length of zero is an empty array.

There are several operations you can do on an array. Push an element means adding a new element at the end. On the other hand, popping an element means removing an element from the end. Removing or adding elements in the middle is possible, but it is not something common.

Multidimensional Arrays

We know that you can a value of any type in each element of the array. Well, that’s exactly true, and it means you don’t have to limit yourself to strings or integers. Each element can be another array, so that you have an array of arrays.

If an array can be a good representation of a string, an array of arrays can be a good representation of a table. In this type of structure, you have two levels of array. One outer level, and one inner in each element. As such, we call it a 2-dimensional array (or bidimensional array).

In this structure, we generally use the outer array to represent rows, and the inner arrays to represent columns. Note that, unlike in the picture, each inner array may have a different length. It is also common to name the outer index i and the inner index j.

A Bidimensional Array in JavaScript can be seen as a Matrix that we can walk with two indexes, often we call them i and j
Bidimensional Array in JavaScript, it looks like a matrix or a table.

That’s nice, but why limit ourselves to two dimensions only. We can easily create an array of arrays of arrays, effectively resulting in a 3-dimensional array. Here, each element is an array of arrays. To i and j, we can ad k as an index.

A 3-dimensional array in JavaScript, it looks like a cube or like coordinates in space
JavaScript tridimensionl array, it looks like a cube or like coordinates in space.

We can clearly see where this is going. Even if it is difficult to represent, you can have an array with 4, 5, 6, or more dimensions. You can have as many dimensions as you need or want. Thus, we can say that we can create multidimensional arrays (or n-dimensional arrays).

Implementing Arrays in JavaScript

Creating the Array

The first thing we have to do is create an array. To do that, we use the square brackets notation, which means a sequence of items. An array, indeed. Between those brackets, we can list the elements we want in our array, separating each from the next with a comma. We don’t need to specify the index, they will be added automatically from zero and going up.

let a = [1, 2, 3, "test"];

Obviously, we have the option to also use an empty list, an array with no elements. We will always be able to add more elements later.

let a = [];

Working with Array Elements

Normally, you don’t want to manipulate the entire array. You want to access a specific element and read its value or change it. Here we need to use indexes. Suppose we define the array from the previous example.

let a = [1, 2, 3, "test"];

Now, we can access each individual value of that array by using the square bracket notation. Unlike the square brackets used during the assignment, here we put the index we want within the brackets, as follows.

a[0]; // is 1
a[1]; // is 2
a[2]; // is 3
a[4]; // is "test"

We can use this syntax to read values, or to set values.

console.log(a[1]); // 2
a[1] = "Now it will be a string";
console.log(a[1]); // "Now it will be a string"

Pushing & Popping

To start, we can check the length of an array – the number of elements it contains – with the length property.

a.length; // 4

To add an element to the end of the array, we can use the push() function. In that, we need to provide the value we want to add at the end:

a.push(10);
a.push("I will be added at the end");

Instead, with the pop() function we can get the value of the last item from the array, and also remove it from the array at the same time. Take a look at this example.

let fruits = ["Kiwi", "Banana", "Mango", "Apple"];
console.log(fruits);
console.log(fruits.pop());
console.log(fruits);

Basically, we define an array and print it. Then, we pop the last element and print it (“Apple” in this case), and then print out the array again. The output of this whole operation will be the one below.

Array(4) [ "Kiwi", "Banana", "Mango", "Apple" ]
Apple
Array(3) [ "Kiwi", "Banana", "Mango" ]

However, just with push() and pop() we are limited in what we can do. We need something more powerful.

JavaScript Array Splice

With the splice() function, we can alter the content of an array as we want. We can modify, remove, or add elements at any point in the array. Not just at the end, not just at the beginning, but at any point in-between.

If push() wanted only to know the value of the element to add, splice() is more complex. It needs to know where to start, how many cells to override, and one or more items to add. The syntax is the one below.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

All these square brackets in the syntax only mean that the parameters are optional because the only mandatory one is start. Furthermore, this function will give you back the items that have been deleted, much like pop(). All this may seem a little complex, but it’s easier than you think.

The splice() function tells to add some items at a specified index in the array. That’s not the end of it. We can also tell how many items we want to delete after that index. So, if we want to add an item and delete zero, the new item will be added in the desired position, and all items after that position will be shifted to make room for it. Instead, if we want to add an item and delete 1, then the new item will replace the existing one in that position.

let fruits = ["Kiwi", "Banana", "Mango", "Apple"];
console.log(fruits);
// Add Orange at index #2, and also remove that item (Mango)
fruits.splice(2, 1, "Orange");
console.log(fruits);

This script will result in the following output.

Array(4) [ "Kiwi", "Banana", "Mango", "Apple" ]
Array(4) [ "Kiwi", "Banana", "Orange", "Apple" ]

Using Splice to Delete Items

Think about a different example. We may want to add zero elements and delete 1. In this case, we can simply delete any item from any point in the array.

let fruits = ["Kiwi", "Banana", "Mango", "Apple"];
console.log(fruits);
// Delete Mango
fruits.splice(2, 1);
console.log(fruits);

That yields the following.

Array(4) [ "Kiwi", "Banana", "Mango", "Apple" ]
Array(3) [ "Kiwi", "Banana", "Apple" ]

Worth noting, whenever you splice or do any array operations, indexs are recalculated. This means that Apple was at index 3 before the split, but obviously, it will be at index 2 after the split. That’s because it becomes the third item from being the fourth, and the index starts always at zero.

Looping on Arrays

Arrays are a wonderful type of variables to play with loops. Naturally, loops allow you to iterate on something and do the same things on many instances of it. An array it is a list of values that is perfect for that.

Need a refresher on JavaScript loops? Check out this tutorial.

The key for loops is, instead of referencing the array index with a static value, we can use a variable. Often, we call that variable i, that’s short for index. In the following example, we calculate the maximum value in the array.

let items = [1, 20, -1, 10, 35, 3, 0, 20, 11, -21];
let maxIndex = 0;
for (let i = 0; i < items.length; i++) {
  if (items[i] > items[maxIndex]) {
    maxIndex = i;
  }
}
console.log("The maximum is " + items[maxIndex] + " at index " + maxIndex);

Here, first, we define an array and a variable to keep the index of the maximum item in the array. Since we don’t know where the maximum is, we start at zero. Then, we loop for all the items in the array with a for loop. In each iteration of the loop, we check the item in that given i position against the maxIndex position. If it’s greater, we update the maxIndex position. Finally, we print out.

JavaScript Arrays for Full Stack Developers

This JavaScript tutorial is part of a broader course on Full Stack Development, which is available for free. As part of this course, we are building a pretend Bakery Store website to test whatever we learn. You can find that on GitHub.com here. Pretty much like any tutorial in the course, we can try out an exercise on arrays.

So here’s the exercise.

The Assignment

For this assignment, you will have to create the code that looks through numbers in an array and find prime numbers. Any prime number found is to be stored in a separate array, called primes, which at the end is to be printed out. Imagine with the following setup:

let source = [1, 2, 13, 147, -1, 45, 23, 29, 31, 32, 37, 40];
let primes = [];

At the end of your code, primes should contain the following values, that you should also print out.

Array(6) [ 2, 13, 23, 29, 31, 37 ]

In case you need a math refresher, a prime number is any number greater than 1 that can be only divided by one or by itself.

Try working on this problem on your own before looking at the solution below. It can be a little challenging, but it definitely trains you to work with arrays and loops, as well as sharpening your thinking.

The Solution

As always, you can find the complete solution on GitHub.com by looking at the code from this commit. However, here we dive into the explanation.

So, basically, we need to do two things. First, we need to loop through all elements in our source array. Second, for each element, we need to identify if it is prime. To do that, we need to brute force our way into trying any division.

Let’s start constructing the skeleton of our code.

let source = [1, 2, 13, 147, -1, 45, 23, 29, 31, 32, 37, 40];
let primes = [];

for(let i=0; i < source.length; i++) {
  let prime = true;
  if (prime) primes.push(source[i]);
}

console.log(primes);

As you can see, we will assume that every number is prime (let prime = true). Then, we will have to add some code to actually check if that is true. If that’s not the case, we set the value to false and skip adding to primes.

Since prime numbers are always greater than 1, we can exclude any number that is 1 or less. We can do that as first thing in our loop: if our number is greater less or equal to 1, we completely skip the iteration (we use the continue statement).

Then, the nasty stuff comes in. We basically need to try any number from 2 to our number less 1 to see if dividing by it generates a remainder. We use the module function (%) for that. If there is no remainder, the number can be divided and it is thus not prime. So here’s our final code.

let source = [1, 2, 13, 147, -1, 45, 23, 29, 31, 32, 37, 40];
let primes = [];

for(let i=0; i < source.length; i++) {
  if (source[i] <= 1) continue;
  let prime = true;
  for (let j=2; j < source[i]; j++) {
    if (source[i] % j === 0) {
      prime = false;
      break;
    }
  }
  if (prime) primes.push(source[i]);
}

console.log(primes);

Keep in mind that this code can be optimized way more. Here we are executing some operations unnecessarily. We may want to leverage the prime numbers that we already found to avoid recomputing for them, for example.

In Conclusion

With arrays, things start to get interesting. In fact, if with variables we were limited on what we could represent, with arrays we are not anymore. In fact, having arrays can be enough to represent any construct or complex model of reality.

However, that doesn’t mean it is the best way to do it. We have other data structures that allow us to be even more proficient and write better code. Before we introduce them, however, we should focus a little bit on our code reusability and logical grouping. That’s what we will do in the next tutorial of this course.

Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.
Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.

Alessandro Maggio

2021-01-28T16:30:51+00:00

Unspecified

Full Stack Development Course

Unspecified