Build Up Your Data - Building and Using Arrays in JavaScript

Learning to build and use Arrays correctly is a fundamental part of your JavaScript journey. So what is an Array and how we deal with them? An Array is a collection of values. Think of it as a variable that can store multiple items. For example, in a variable we could store the name of one person:

var name = 'Jeff';

But, in an array we can store multiples names:

var names = ['Jeff', 'Kim', 'George','Lucy'];

We'll get to the syntax of building an array in a bit but in the example above the variable 'names' is storing more than just one string. Arrays can also store numbers:

var numbers = [4, 2, 7, 9];

And, you even can mix the types of values:

var items = ['Julie', 3, 'Tom', 7, 9, 'Kathy'];

We are not limited to just four values like our examples. We can store as many values as needed in our Arrays.

Ok, so what is this syntax we are seeing? You start just like you would a variable but instead of declaring a value you assign a list of values inside a pair of square brackets. Each value is separated by a comma.

You may also see Arrays created like this:

var items = new Array('Jeff', 'Kim', 'George', 'Lucy');

This technique also creates an Array but it is more verbose and can create some interesting issues. If we create an Array with numeric values like this we are fine:

var numbers = new Array(4, 2, 7, 9);

But if we try to create a single value Array using numbers we get an empty Array with that many placeholders:

var numbers = new Array(40);

This creates an Array named 'numbers' that has 40 values, all null or unassigned. Using our bracket notation, we do have this problem:

var numbers = [40];

That creates a 'numbers' Array with a single value of 40.

In our examples we also assigned the new Array with values, in the brackets. Much like variables, you don't have to assign values immediately upon creating the Array. You could initialize the Array without assigning values like this:

var names = [];

Later we can come back to the Array and assign values, but first we need to understand how we access those values in the Array.

We can't just write the Array name to the document like we would a variable. We have to tell the script which value in the Array we want to retrieve. Let's take our 'names' Array as an example:

var names = ['Jeff','Kim','George','Lucy'];

If we would like to access the second name in the Array we would write this:


We indicate the Array item we want in square brackets immediately after the name of the Array. Why not a number 2 in our example? Good question. You would think that if we want the second object we would write: names[2], right? But Arrays use indices, or index numbers, to indicate which positions the item is assigned. In programing we always start counting with the number 0. So you see, the first position is index 0, the second position is index 1, and so on.

Here is how the Array might look to the program. Not entirely precise but good enough for our example.

names['Jeff', 'Kim', 'George', 'Lucy']
[0]    [1]     [2]       [3]

Below that I put the index number of each item. Can you see the correlation? So names[1] would produce 'Kim'.

Now that we understand how to access a particular position's value in Array we can see that we can also change or assign that position a value:

names[1] = 'Tom';

Now our Array looks like this:

names['Jeff', 'Tom', 'George','Lucy']

'Tom' replaced 'Kim' in index 1. Remember when we created the Array without assigning values? Now we know how to assign values if the Array wasn't initialized with them:

var names = [];

names[0] = 'Mike';
names[1] = 'Sally';
names[2] = 'Steve';
names[3] = 'Chris';

Whew, that took a little longer than creating the values when the Array was initialized. So, why would we use this technique instead? This is useful if we don't know what these values are going to be when the program starts running. We may need to assign these later based on other data, a calculation, or user input.

Now that we know a little about creating Arrays let's look at a few more examples:

Notice how we wrote the Array in the example above. For long sets of values it is common to put each value on its own line, but also notice the closing parenthesis is on a separate line at the end. This is considered good coding practice that helps the programmer see exactly where the Array set ends. Here we can also see how the Array is used in our 'document.write' statement.

Here is an example of using information entered by the user and storing it in an Array (click the CodePen box to load and run the example, you will be prompted to answer a few questions that will be used in the Array):

Here we initialized the Array without values so we can ask the user for some information and store it in the Array. We then used those values in a 'document.write' statement. You can see here we were also able to write the 'document.write' statement on multiple lines but note, we can only break the line before or after a concatenation symbol (+), not in the middle of a string. This helps to make complicated statements more readable for the developer.

Unlike variables, Arrays have a property associated to them call the 'length'. We can use the 'length' property to discover how many values the Array is storing. This is very useful for those times when we are allowing the user's input to build the Array, or an outside resource. We access properties by attaching the property name to the Array name using the dot(.) syntax. Observe:

We can also use the length property to add a value at the end of an Array because the length would be the next available index at the end:

The 'toString' code you see in this script is an example of a method you can use on Arrays. To learn more about methods see the article, 'Get Methodical - Using Array Methods in JavaScript'.

Learning to build Arrays properly will help us store and use larger sets of data without creating, and coming up with, multiple variables. If you would like to learn more about using Arrays and the JavaScript language visit JavaScript Training Courses on our website for some excellent classes on the subject.


Onsite JavaScript training

Through our network of local trainers we deliver onsite JavaScript classes right across the country. Obtain a quote for onsite JavaScript training.

To view a sample of our past students testimonials, please click on the following link: Javascript testimonials.