Arrays
This lesson is part of the Web Programming 1 Course.
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:
const myTestScores = [96, 85, 89, 77];
console.log(myTestScores);
The myTestScore variable stores 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:
const 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. For example:
var mixedArray = [6, "bob", false];
Array Elements (not be be confused with HTML elements)
The values stored in an array are called elements. The mixed array above stores 3 elements (6, "bob", and false). The term 'elements' can be confusing for students of this course because we have been talking about HTML elements since the very first lesson. Here's an example of a term that has different meaning depending on the context. HTML elements are not the same thing as array elements (although it is possible to create arrays of 'element objects' as we'll see in an upcoming lesson).
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 retrieve an element from an array by using its index number and bracket notation, like so:
console.log(myTestScores[0]); // this will log 96, which is the first element in the myTestScores array
So, to access an array element in your code, type in the name of the variable that stores the array, then use bracket notation and an index number to specify which element you wish to access.
You can also use index numbers and bracket notation to assign an elements to variables, like so:
const firstTest = myTestScores[0];
const secondTest = myTestScores[1];
const thirdTest = myTestScores[2];
const fourthTest = myTestScores[3];
console.log(firstTest, secondTest, thirdTest, fourthTest);
Again, remember that index numbers start with 0. So, the index of the first element in an array is 0, not 1.
Updating Elements in an Array
You can change values in an array by using bracket notation and an index:
myTestScores[3] = 100;
console.log(myTestScores);
Adding Elements to an Array
In JavaScript you can easily add elements to an array (some languages don't allow you to do this after an array variable has been declared). To do this, you use bracket notation and the index number like so:
myTestScores[4] = 77;
console.log(myTestScores); // the log will show that 77 has been added to the array at index 4
You can declare a variable that stores an empty array, and add elements to it later in your program:
const pets = [];
pets[0] = "Buster";
pets[1] = "Fido";
console.log(pets);
This can come in handy when you want start with an empty array and add elements to it as your program executes. For example, when you want user input to populate the array.
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.
To access the length property of an array, use dot notation just like you would for accessing a property of any other object:
console.log(myFriends.length);
Here's a handy trick for adding an element to an array which makes use of the length property:
myFriends[myFriends.length] = "Pat";
When the browser executes the line of code above, 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.
The above line of code is equivalent to this:
myFriends[3] = "Pat";
But there are cases when you should use the length property rather than a specific index number when adding elements to an array. We can discuss these cases (and other ways of adding elements to an array) in class.
In addition to the length property, arrays are object that have many methods that are very useful to programmers. We won't get into them right now, but I'll show you one which allows you to add an element to an array (so, you could use this approach instead of using the length property):
myFriends.push("Chia");
In this example we are using the push() method of the myFriends array/object to add the string 'Chia'.
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:
// create an empty array and assign it to the 'people' variable:
const people = [];
// add an object as the first element in the array:
people[0] = {firstName:"Lu", lastName:"Vang", age:22};
// add another object as the second element in the array:
people[1] = {firstName:"Lena", lastName:"Severson", age:63};
console.log(people);
The code sample above uses 3 statements to create and populate the array. The first statement declares the empty array. The second statement adds an object to the array. And the third statement adds yet another object to the array.
You could create and populate an array in a single statement like so:
const books = [{title:"Harry Potter", author:"Rowlings"}, {title:"The Sun Also Rises" author:"Hemmingway"}];
This line of code is very hard to read, but if you look closely you'll see that there are two objects (enclosed in curly braces) inside the square brackets.
A better way to write this code is to spread it out across multiple lines like so:
const books = [
{title:"Harry Potter", author:"Rowlings"},
{title:"The Sun Also Rises", author:"Hemmingway"}
];
Note that each object is on it's own line, and that the line is indented so that we can clearly see that the objects are enclosed within the array.
There are a few ways that you code access properties of an object that is in an array, you could use bracket and dot notation like this:
console.log(books[0].title);
Let's analyze what's being passed into the console log in this example. The expression books[0] will evaluate to the first element in the array. This element happens to be an object that has a 'title' property. So the dot operator can be used to access the title of the book. You should see "Harry Potter" in the console log when you run this code.
Another way you can access a specific property of an object that's 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:
const b = books[0];
console.log(b.title); // shows just the title of the book stored in b
console.log(b); // shows the book object stored in b
In this example, we declare the b variable assign it to the first element in the books array
If you wanted to change the title of this book, you could do so in one of two ways. You could change it by accessing the book directly from the array, like so:
books[0].title = "Harry Potter and the Sorcerer's Stone";
Or, if you want to use the b variable that was previously declared, you could do this:
b.title = "Harry Potter and the Sorcerer's Stone";