JavaScript Arrays
This tutorial is part of a web programming course for people who have no programming experience.
An array is a collection of data. When we write programs, we often need to work with collections of data. For example, you probably wouldn't write a program to keep track of a single book, instead it would be more useful to keep track of a collection of books (maybe you are building software for a public library).
JavaScript, like many other programming languages, allows us to work with collections of data by using arrays.
In previous lessons, we have used variables to store a single piece of data, such as a number, string, or boolean. Arrays allow us to use a single variable to store multiple values, consider this example:
var myTestScores = [96, 85, 89, 77];
console.log(myTestScores);
This is an array of numbers. Let's take a minute to discuss the syntax used to create this array. Notice that there are square brackets enclosing the array []. And notice that the values in the array are separated by commas.
The previous code sample demonstrates an array that stores numbers. Here's one that stores strings:
var myFriends = ["Joe", "Betty", "Sally"];
console.log(myFriends);
Some languages require that arrays store values that are the same data type. But JavaScript allows you to mix data types within an array.
var mixedArray = [6, "bob", false];
The values stored in an array are called elements (not to be confused with elements in HTML). The mixed array above stores 3 elements.
Array Indices
Each element in an array has a specific position, which is known as the index of the element. For example, in the mixed array above, the first element (the value 6) has an index of 0. Array indexes start at 0 in most programming languages, this is something that can trip up beginners, but with enough practice, you'll quickly get used to this.
You can retreive values out of an array by using it's index number along with bracket notation.
console.log(mixedArray[0]);
You can 'get a handle' on each element in an array and assign it to a variable like so:
var myTestScores = [96, 85, 89, 77];
var firstTest = myTestScores[0];
var secondTest = myTestScores[1];
var thirdTest = myTestScores[2];
var fourthTest = myTestScores[3];
console.log(firstTest, secondTest, thirdTest, fourthTest);
Again, be careful to remember that the first element has an index of 0. Also notice that we are 'getting a handle' on each element in the array by assigning it to a variable.
We can also change values in an array by using bracket notation and an index:
myTestScores[3] = 100;
console.log(myTestScores);
It's common to start with an empty array, and then build it up as the program runs. Notice in the code sample below, that we start with an empty array, and then we prompt the user to add elements.
var testScores = [];
testScores[0] = prompt("Enter your first test score.");
testScores[1] = prompt("Enter your second test score.");
testScores[2] = prompt("Enter your third test score.");
console.log(testScores);
Arrays are Objects
Arrays are actually a special type of object in JavaScript. And like other objects, they have properties and methods that we can use. We'll talk more about array methods later, but for now let's go over the length property of an array. The length property will tell us how many elements are in an array. Note that the length will always be one greater than the highest index in an array. This makes sense when you remember that the index of the first element is 0. To access the length property of an array, use dot notation just like you would for accessing a property of any other object:
var myFriends = ["Betty", "Sally", "Bob"];
console.log(myFriends.length);
Remember our discussion about bracket notation when when we first discussed objects? The code that goes inside the brackets can be an expression. So you can use the length property when you want to add an element to an array, like so:
myFriends[myFriends.length] = "Pat";
console.log(myFriends);
When the browser executes the last statement, it will have to evaluate the myFriends.length expression so that it knows the index of the element you would like to set to "Pat". In this case myFriends.length evaluates to 3. There is no element at index 3 (because the highest index is 2, where "Bob" is stored), so "Pat" will be added to the array at index 3.
Here's another trick that makes use of the length property, if you want to 'get a handle' on the last element in an array and assign it to a variable, you could do something like this:
var myLastFriend = myFriends[myFriends.length - 1];
console.log(myLastFriend);
Look at the expression inside the square brackets, and remember that the highest index in an array will always be one less than the length of the array. Here's another example that uses an expression inside the brackets:
var x = prompt("Enter a valid index number for the myFriends array");
var selectedElement = myFriends[x];
if(selectedElement != undefined){
alert("The value of the element at index " + x + " is: " + selectedElement);
}else{
alert("There is no element at index " + x + " in the myFriends array.");
}
Arrays of Objects
We have seen that you can put various data types inside of arrays, such as numbers, strings, and booleans. Arrays can also store objects. This allows us to model collections of real world objects, which is very useful for processing data in our programs. Take a look at this array:
var books = [];
books[0] = {title:"Harvey Porter", author:"Rowlings"};
books[1] = {title:"The Sun Also Rises", author:"Hemmingway"};
We start out by creating an empty array in the first statement. Then we add an object at the first position (index 0). Then we add another object at the second position (index 1);
This approach required us to write three statements to create and populate the array. But we could do it all in a single statement like this:
var books = [
{title:"Harvey Porter", author:"Rowlings"},
{title:"The Sun Also Rises", author:"Hemmingway"}
];
Note that I broke the statement up into separate lines, and put each object on its own line to make things easier to read. Also note that all the elements in the array are indented so that it's easy to visualize that the objects are nested within an array. Have I already ranted about the importance of formmatting your code properly in this course?
There are a few ways that you code access properties of an object that is in an array, you could use bracket notation like this:console.log(books[0].title);
Let's verbally evaluate the parameter that is being passed into the console.log method in the above code sample. The expression books[0] will evaluate to the first element in the array. This element happens to be an object with a 'title' property in it. So we can use the dot operator is used to access the title of the book. You should see "Harvey Porter" in the console log when you run this code.
Another way that you access a specific property of an object in an array is to 'get a handle' on the object first by assigning it to a variable, and then using the dot operator to access the property:
var b = books[0];
console.log(b.title);
If you wanted to change the title of this book, you could do so in one of two ways:
books[0].title = "Henry Popper";
// or
b.title = "Harry Potter";
console.log(books);
Summary
We shall soon discusss how you can write some very powerful programs when you start using arrays of objects! In the program that I teach at Western Technical College, the students are required to learn a good deal about databases. After learning the basics of programming and databases, they learn to fetch rows from a database table and store them in an array of objects. This allows you to build extremely powerful software applications.
NEXT LESSON - Loops