Arrays in JavaScript

byTrevor PageonJuly 26, 2015

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.
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.

Using square brackets (aka. array literal)

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:

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:

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:

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?

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:

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!

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:

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.

Hey Trevor. I was wondering. I’m doing a codecardio challenge to try and get into a programming course and one of the challenges was.

//create a function named ‘last’ that returns the last object from a given array
//HINT: try to make it so that no matter the size of the array, your function will still return the correct value.

I looked around online and found that I could make sure it would pull that last object from the array with ..
var arr = [1, 2, 3]

function last(arr)
{
return(arr[arr.length-1])
}
but my question is what makes
return(arr[arr.length-1])
work? When I run it with just (arr.length-1) with the above function it returns with 2. So why is the arr[] important to this function? Thanks

You need to understand two different aspects to understand how this works.

1. There’s a way to get the total length of any array, it’s by using the “.length” property.
2. In order to access an element from any array, you use the square bracket notation with an index inside of it. i.e. [0] for the first element, [1] for the second, [2] for the third etc.

Once you combine these two concepts together, you get the code that you’ve posted above.

arr[arr.length-1] will return the last element in the arr array. This is the case because arr.length-1 returns the length of the array (which in the case of your example is 3), then you subtract 1 from that number because arrays use a zero based indexing system.