Web development explained for normal people! 🖥 🚀

The complete guide to JavaScript arrays

Arrays are a very useful part of JavaScript, and come in handy for things from text manipulation to image processing!

Whether you’re a complete beginner or coming for some more advanced array functions, this article is for you!

The contents of this article:

First of all, sorry for another clickbait-y title. However, I promise that this is a complete guide! In fact, so complete that it needs a table of contents! I never thought I’d have to do this, but here we go…

I know that some of you may already know the basics of arrays, in which case feel free to go to whichever of those sections you don’t know already. Otherwise, start from the beginning and enjoy the ride!

Note that if you’re a complete beginner to arrays, you might want to only read part of this article for the moment. Or, depending on your learning style, you might want to read the whole thing! If you’re going to only read part of it, I recommend that you stop after How to reference a value in an array or array.includes(). But don’t forget to scroll down for the conclusion!

Let’s get started already!

💡 Follow along!

First of all, I encourage you to follow along in this article. It will help you learn better, and also help you to remember what you have done. Let’s start by making a new HTML file with a <script> tag in it:

Once that’s done, open it up in your web browser and you’re ready to go! (don’t forget to save and reload the page every time you make a change)

What is an array?

An array is simply a list of values. Here is what an array looks like in JavaScript:

var myArray = ['String', 8, true, myFunction()];

As you can see, an array is a value usually assigned to a variable. In this case, we’re assigning it to the myArray variable. So we start by saying var myArray = . After that, we have a set of square brackets. Inside the square brackets are four items, separated by commas. These items can be any type of value — a string, number, boolean, function, object, or even another array! (I’ll get onto that further down)

How to reference a value in an array

Normally, we might write something like this:

alert(1234);

However, what if we wanted to alert the 8 in the array above? Here’s how you’d do it:

alert( myArray[1] );

What!? But 8 is the second item in the array! This is because…

Arrays start at 0!

What I mean by this is that if you want to refer to the first item of an array, you say array[0], not array[1]. The reason isn’t that important, but the point is that arrays start at 0. In nearly every programming language, in fact. Because arrays start at 0, it means that all the other numbers are one less than you expect. So above, the second item became myArray[1]. Similarly, the fourth item would become myArray[3]. The number inside the square brackets (eg. 1 from above) is the index of that particular item in the array.

💥💥💥💥💥💥Arrays start at 0!💥💥💥💥💥💥

Sorry for all the emphasis (😂), but this is a very important point. You’re going to want to remember it, or else you will get very confused later on.

Array functions

Now we’re done with the basics, let’s look at some functions that we can use to create, convert, and manipulate arrays. Let’s get right into it! (be excited 😉)

For this section, I’m going to be using console.log instead of alert, so we can see properly what is an array and what isn’t. To open the console in your browser, right-click and then click ‘Inspect Element’ (or something similar to that). Then click the ‘Console’ tab up the top. It looks something like this:

string.split()

We can use .split() to turn a string into an array. Here is an example:

As you can see, we split by an empty string ('') and ended up with each character separated in a nice neat array! This can come in handy when you want to manipulate text in certain ways.

Moving on!

array.join()

This is the exact opposite of .split(). Instead of turning a string into an array, we are turning an array into a string! The parameter is what the items will be separated by in the string. For example:

array.lastIndexOf()

So, .indexOf() should really be called .firstIndexOf(). But it isn’t, because JavaScript is weird. But if we want to find the last index of a value, we can use .lastIndexOf()! It works just like .indexOf(), except that it finds the last, not the first, of a value. Let’s try it in our array from above:

array.find()

.find() finds the first item in an array which passes a certain test. The input parameter is a function which either returns true or false. If it returns true, it means that the item has passed the test. If it returns false, it means the item has not passed the test. Here is an example, which finds the first item over 10:

As you can see, the function isOver10 will return false until num is greater than 10. So, .find() will keep looping through the array until isOver10 finally returns true (meaning the number is greater than 10).

Time to try it out! See if you can find the first vowel (a, e, i, o, or u) in the word stronger…

Your program should end up logging 'o'. Note the letter.toLowerCase() — we want it to count even if the vowel is a capital! As you can see, arrays have many cool uses!

array.findIndex()

array.findIndex() simply returns the index of what you’d get if you did .find(). For example, in the puzzle above, instead of outputting 'o' it would output 3 (because the index of 'o' in the array is 3).

array.map()

array.map() returns a new array with the outputs of calling a function on every element in the array. For example, let’s say you wanted to increase every element in an array by 2 — you could write:

By the way, good job for hanging in there. I know it’s a lot to process all at once, so take it slowly if you need to. You can always come back to this article for reference later.

array.filter()

array.filter() returns a new array with all the elements from the existing array that past a test. Like array.find(), the test is a function which returns true if the element passes and false if it doesn’t pass. For example, let’s say that you wanted to filter an array so that it only contained numbers below 5:

As you can see, 14 and 662 have been removed because they are greater than 5!

Let’s make a fun program which removes all vowels from a sentence, leaving only the consonants, spaces and punctuation. As a bonus, try to pronounce it all at the end!

You can use your isVowel(letter) function from earlier, and turn it into an isNotVowel(letter) function. This means we want the opposite output! To do this, you can put a ! in front of the brackets like so:

array.reduce()

array.reduce() turns an entire array into one value. What?! Don’t worry. All this means is that it loops through every element in the array, does something with them and returns a final value. An example of this is adding all the elements in an array of numbers. We’re taking an array, and end up with just one value (the sum). To do this, .reduce() goes through each of the elements from left to right.

array.reduce() takes a function as input, just like the previous few array functions we’ve looked at. However, instead of the function having one parameter (for the element) it has two: one for the element, and one for the existing value from all the previous items in the array.

Let’s try adding all the elements in an array:

[2, 3, 5, 110]

For this, our function would look like so:

function addTogether(total, num) {
return(total + num);
}

Let’s go through what would happen here.

The program would start on the first element in the array, 2. The total so far is 0, and the number is 2. So we add these together and get a new total of 2. Next up is 3. The total is now 2, which means that we add 3 to 2. This gives us a new total of 5. Now, our total is 5 and our new number is also 5. We add these together and get a new total of 10. The total is now 10 and the new number is 110. We add these together, giving us our final output of 120.

NOOOOOO! That isn’t how counting goes! Let’s see if we can manage to sort it numerically.

The array.sort() function can have an optional parameter. This is a function, which compares two elements in the array. The function takes two inputs — the two elements to compare. If it outputs a negative number, the first input element comes before the second input element. If the function returns a positive number, the first input element comes after the second input element. You’ll see what I mean as we go create our numerical sorting function…

First, let’s make our actual function.

function compare(num1, num2) {
}

In our sorted array, we’ll want a smaller number to come before a larger number So let’s say our function is asked to compare 3 and 5. We’ll want to output a negative so that 3 comes before5 in the array. If we had something like 6 and 1, we’d want to output a positive so that 6 comes after1.

A cool way that we can do this is with subtraction! If we subtract the second number from the first number, both of these cases work. 3 - 5 is negative, which is what we want. 6 - 1 is positive, which is also what we want! So our sorting function would look like so:

array.splice()

The first parameter is the index in the array where you want to start from. Next is the amount of elements in the array that you want to remove from there. This can be 0 if you’re only adding elements! After that, you can list any elements you want to add in at that spot as parameters. Note that .splice() inserts the items before the element with that index.

Let’s do an example. We’ll use the following array:

[1, 2, 3, 4, 5]

Time to try splicing things up! (sorry for the puns 😭)

Let’s remove the 3 and replace it with an 8 and a 9. First of all, we need to provide the index — which in this case is 2. We also need to provide the number of items we will be removing, which in this case is just 1 — the 3! Next, we need to specify all the items we want to add. The final function would look like this:

Note that we didn’t say console.log( myArray.splice(2, 1, 8, 9) );. This is because the function doesn’t create a new array — it just modifies the existing one! However, .splice() does actually have an output. It outputs an array of all the elements that were removed! Try it out…

There we go! That’s all the array functions for today, and probably all that you’ll need for quite a while! Good on you for making it through this far 👏

We’re nearly at the end of this article. However, there’s one more thing to cover…

Nested arrays

I said near the beginning of this article that arrays are just lists of values — and that those values can be anything! But what if some of those values were arrays? Yup, that’s right. Introducing….. An array of arrays! (*slow clap*)

var nestedArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];

Depending on your personal taste, you may prefer to express it like this:

var nestedArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

It’s entirely up to you which you decide to do! (yay rhyming)

But how would you access an element in this nested array? Let’s try and get the 6.

First of all, think about how you’d get the array containing the 6. It’s the second item in the nestedArray array, meaning we can refer to it like this:

nestedArray[1]

Now, let’s say that nestedArray[1] was actually just an array named a. How would you access the 6? You’d simply say:

a[2]

So, we just need to replace the a with nestedArray[1]! This gives us….

nestedArray[1][2]

Tada! This is how you get an element in a nested array! Try and get the 8…

nestedArray[2][1]

By the way, there’s no reason why you can’t have an array in an array in an array. Before I show you this, just a warning: don’t panic! It’s a huge confusing array, but you really don’t need to worry about it unless you’re curious. Here it is…

Remember, if this confuses you don’t worry! You don’t need to fuss about it.

But what are actual uses for nested arrays? Well, nestedArray[2][1] looks remarkably like coordinates. It has two position values, which could be used as coordinates to track something’s position! And nestedArray[2][1][0] can be used as 3D coordinates! As such, nested arrays come in handy a lot when programming games. Developers will often use a nested array as the ‘grid’ on which a game is played, and store information about what is at each location. Nested arrays are also often used in image processing, where the coordinates are the coordinates of pixels in an image.

Nested arrays are quite advanced stuff, so you will probably only use them much further down the track. However, for the sake of completeness, I’ve added them in here anyway.

Conclusion

This article is meant as a complete to JavaScript arrays, but you may not need to know it all at the moment. Just start with the basics I discussed near the top, then go further when you’re confident and ready.

Anyway, wow! This is the longest article I’ve ever written on Code The Web, with close to 5,000 words! It’s taken me nearly 5 hours to write this article, and my fingers, eyes, and brain are all hurting! I think I’m definitely in need of a coffee. So if you got something out of this article, I’d really appreciate if you paid whatever you want and bought me a coffee or two or three on my Buy Me A Coffee page. Thanks! 😅

If you know a fellow human who would get benefit from this article, share it with them! They’ll thank you for it… I’ll make it easy for you by sticking this nice, juicy link right here…

I know that this was a challenging article, so if you need help don’t hesitate to leave a comment, contact me via email or use the fancy chat widget that should be in the corner of your screen!

Have fun, and I’ll see you next time where I’ll be talking about something similar to arrays but different — Objects! See you then…

P.S. I’ve started a Patreon page! I’d really appreciate it if you supported me with an ongoing donation — even if it’s only $1 a month! Rewards include getting featured on a special thanks page with other awesome people, and getting massive discounts off anything from Code The Web (I’m currently not selling anything, but my first book will be done in a few weeks!)

If there’s anything else which you feel you should get as a patron, feel free to contact me :)