So we've talked a lot already about all the different data types and built-in objects in JavaScript, but not once have I mentioned Arrays.
Arrays In Javascript
The reason for this is that the topic of Arrays is quite a broad one and it will require you to understand many of the base mechanics of the JavaScript language before you can jump in.

Having said that, I believe your moment has arrived, you are now ready.

How to Create an Array in JavaScript

Believe it or not, JavaScript actually has two ways of creating an Array.

  1. Using square brackets (aka. array literal)
  2. Using the new keyword

Creating an Array Using Literals

Here's an example of how to create an Array using the first method:

var myArray = ["first element", "second element", "third element"];

You see here that we've used square brackets to create an array that has three elements. In this case we're storing strings inside of the array, but we really could have used any data type we wanted. You can even mix and match data types in your arrays like so:

var myArray = ["first element", 2, 10.2, {firstName: "Trevor", lastName: "Page"}];

Here we have inserted a string, two numbers and an Object.

This kind of mix and match isn't recommended though, as it's pretty confusing and would be strange to iterate through. But, it's interesting to note that you can do it, right?

Creating an Array Using the new Keyword

Alright, now let's take a look at the second way to create an Array.

It's worth noting that this method for creating an Array isn't recommended as it's not as efficient and has some quirks. So it's always suggested that you create an array using the array literal syntax above.

In any case, you will most likely run into the code that uses the new keyword to instantiate an Array in JavaScript. So let's take a look at an example:

var myArray = new Array(3);
myArray[0] = "first element";
myArray[1] = "second element";
myArray[2] = "third element";

When you place a number inside of the round brackets of the Array instantiation, this tells JavaScript to allocate three spots for the array. However, with JavaScript, arrays are implemented as objects and can therefore be extended beyond what was initially set as.

Just as in most (if not all) programming languages, JavaScript uses a zero based index for its numbering system with elements in an array. This means that the "first element" will be at index 0.

Accessing Elements in a JavaScript Array

As you've seen above, we are able to place elements into our arrays, but we haven't talked about how to retrieve those items.

All you need to do is reference the index of the item you'd like to retrieve with the following syntax:

var firstElement = myArray[0];
var secondElement = myArray[1];
var thirdElement = myArray[2];

Pretty simple stuff. The hardest part is remembering the syntax.

One thing that's interesting to note is that a JavaScript array doesn't give you any errors if you try to access an index that doesn't exist. In the Java language, if you've allotted 3 elements to exist inside the array, then try to access a fourth element, you'd get an IndexOutOfBoundsException… but in JavaScript, all you'll get back is undefined, as you're accessing an element that hasn't yet been created.

Adding Elements to a JavaScript Array

So you've already seen how to place elements in a JavaScript array when it's being created… but what about after it has been created? How do we insert elements then?

There are two ways:

  1. Using the push() method
  2. Assigning a variable to an index in the array directly

First let's look at the push() method:

myArray.push("fourth element");
myArray.push("fifth element");
myArray.push(12);
myArray.push({objectProperty: "someProperty"});

This is also pretty simple stuff, each time you invoke the push() method, JavaScript will add the element you specified inside the round brackets to the end of the array.

OR…

You could just manually specify an index where you'd like to insert an element like so:

myArray[9] = "tenth element";
myArray[99] = "one hundredth element";

In the code above, we just specified the exact index where we'd like to insert an element.

The cool thing about JavaScript arrays is that they don't really function like an array really, they operate like a Map. So you're allowed to have “holes” in the array. As you can see, we assign an element to index 9, and then we assign an element to index 99… again, in Java, this is sinful, but in JavaScript it's perfectly legal.

Again, it's not very useful if you'd like to have consecutive elements being stored, but you are free to utilize an array with gaps if that suits your needs.

Deleting Elements from a JavaScript Array

We know how to add, now let's talk deleting!

One thing I wish the JavaScript Array had was something like a remove or delete method, but alas we must deal with something a bit more complex.

The method used to delete an element or elements from an Array is the splice method.

The splice method can actually be used to delete multiple elements (not just one), and it can even be used to insert elements into an Array at any index. So the splice method is quite flexible, but that's exactly where I think it falls short. It just does too much and therefore I'm always looking up how to delete elements from a JavaScript Array as I keep forgetting how to use it.

Anyway, enough complaining, let's look at an example. Let's say we wanted to implement some code to delete the last element in a JavaScript Array. This is a common task, so it'll be some useful code, here we go:

var myArray = ["first element", "second element", "third element"];
myArray.splice(myArray.length-1, 1);

So, what's going on here is that the splice method takes two parameters by default. Both are required.

The first specifies the index at which you'd like to delete elements, the second parameter says how many elements you'd like to delete.

So in this case, we're passing in myArray.length-1 as the index from which we'd like to start deleting. Since the Array‘s length is 3, this means that we'll start deleting at index 2. Then we specify that we'd like to delete one element, so it will just remove the last element in the Array.

Alright, but I also mentioned that the splice method can insert elements as well! So let's now try and insert an element in the middle of our Array while deleting an element as well… you see how complicated this can get? Jeez!

var myArray = ["first element", "second element", "third element"];
myArray.splice(1, 1, "random middle element");

So, the code above will do two things, first it will delete one element at index 1. Since Arrays use a zero based indexing system, this means that we're deleting the second element… THEN, we are telling it to add the "random middle element", which will add the element at the index that you specified in the first parameter.

So the resulting array will look like this:

["first element", "random middle element", "third element"]

So you see here that the second element has been deleted and it has been replaced with a "random middle element".

It's also pertinent to note that you can add as many elements as you like with the splice method. Here's what I mean:

var myArray = ["first element", "second element", "third element"];
myArray.splice(1, 1, "random middle element", "another middle element", "yet another element", "etc");

The resulting array would then be:

["first element", "random middle element", "another middle element", "yet another element", "etc", "third element"]

Cooooooool.

Alright, then about sums up all the typical things that you can do with the JavaScript Array! For even more fun tricks, check out this article from W3Schools.

And since you've read ALL the way to the bottom of this post, you REALLY need to put your email address in the box below. We've got some great free JavaScript swag to send to you, check out the info in the box below for more details.

Free Java Beginners Course

Start learning how to code today with our free beginners course. Learn more.