Deeper into Javascript  Arrays and Loops

Reading from Javascript & jQuery: The Missing Manual - Arrays (pp 59-66), Loops (pp 93-98), Objects (pp 70-72).
Alternatively, the Chapter 2 of Head First HTML5 has information about Loops (pp 46-51) and Arrays (pp 67-75).
For more interactive examples, check the W3Schools pages: Arrays, for loops, and Objects.


So far we have seen four kinds of data types in Javascript: numbers, strings, booleans, and objects (e.g. Date). A special kind of object that is commonly used in Javascript and other programming languages is an Array. Arrays are very useful to store collections of values together under one name. Let's see some examples:

var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

Notice how we can create an array by simply using the square brackets notation [ ] and separating with comma the values inside them. Such notation is known as creation of an array literal (can you notice the similarity with the object literal?. In books and the Web you will see other ways to create arrays, that are a bit more complex. A common one uses the the constructor notation, see example:

var powersOfTwo = new Array();
powersOfTwo[0] = 1;
powersOfTwo[1] = 2;
powersOfTwo[2] = 4;
powersOfTwo[3] = 8;

As you can see, this is a verbose way for creating and populating arrays with values, and we will avoid it. However, it showcases how we can access the elements of the array: by using index values (which, as always in Javascript will start at 0). Notice how in this case the square brackets are used for another purpose, to access a certain element of the array, based on the value of its index. In English, we read the statement powersOfTwo[0] = 1; as powerOfTwo sub 0 gets value 1. (sub is the short form of the word subscript). Now, let us see a useful example of using arrays for websites.

Exercise 1: Display the day name

As you know, the Javascript object Date has a method .getDay() that returns a number from 0 to 6 to refer to the day of the week, not its name. This makes sense, since weekdays in different countries are named differently. Below is a Javascript program that uses arrays to display the right name of the day based on the language of your browser. The browser is represented within the DOM model by the object navigator. Using the properties and methods of the navigator you can access different kinds of information, such as the browser type or your geolocation.

In the variable dayIndex we store a numerical value (a number from 0 to 6) that represents the day, and then we use that value as an index to access the day name from the weekDays array. Assuming the value for dayIndex is 3, the expression weekDays[dayIndex] will return the value "Wednesday".

Properties and Methods of Arrays

An array object has many useful properties and methods. While you might not need most of them, it's worth to be aware of what's available. W3Schools has a list of all of them, together with snippets of Javascript code to explain each.

Here are the ones you should know:

  • .length - a property that returns the number of elements in an array
  • .push() - a method that adds new elements at the end of an array
  • .indexOf() - a method that returns the index of an element in the array
  • .pop() - a method that removes the last element from an array
  • .sort() - a method that sorts the elements of an array
Play with the following code to understand each of them.

Exercise 2: Array Operations

for loops for Arrays

Imagine that you run a website about new paperback book releases, and every week you have to update one page with the new titles and their prices. Here is the HTML code for a few entries of the page:

<div id="newbooks">
  <p>Mockingjay <span>$4.99</span></p>
  <p>Fahrenheit 451 <span>$2.99</span></p>
  <p>Persuasion <span>$1.99</span></p>

This markup is very simplified, you can imagine that we would also have the author name for every book, together with a link to the description and buy page. Manually updating this content every week is tedious work.

It makes sense to automate this process and because the structure of the page is repetitive, we can use a loop to organize our code. We will show the code and its results below and then explain how it works. Click on the "Execute it" button to see the results in the blue-bordered box.

Exercise 3: Dynamic HTML with Arrays and Loops

For this solution, we imagine that we received two arrays of titles and prices (maybe they were columns in a spreadsheet). By plugging them in in the Javascript code, the page will show the new content every time we have new data.

Let us explain each line of code.

  • Line 1 declares the array books that stores a list of book titles.
  • Line 2 declares the array prices that stores the corresponding prices for each book. These two arrays have the same length.
  • Line 3 declares a variable that will refer to the div element in the HTML page where the book titles will be displayed. (In our example, it refers to the blue-bordered box.)
  • Line 4 declares a variable that will store the HTML code we will generate automatically. Initially its value is an empty string.
  • Line 5 is the statement that declares a for loop. This loop repeats the same statements (line 6 and 7) inside its { } for a certain number of times (the length of the array). Some time you'll see the expression i++; as a shortcut for i = i + 1;.
  • Line 6 assigns to the variable oneLine the string value created by concatenating together some HTML tags and their text values from the two arrays of data.
  • Line 7 is a reassignment statement. Every time it concatenates new lines of HTML code to the variable html.
  • Line 8 sets the innerHTML property of divElement to the created new HTML code.

Play with the given code. Add more book titles and prices to the two arrays or change the order of the items. Then execute the code again. Notice how every time it does the right thing. (If you are wondering about the styling of the created elements, our HTML file has document-level CSS styles for the elements #newbooks p and #newbooks span.)

Let us now turn our attention to the for loop, which was a new construct you have not encountered before.

for loop syntax
The syntax of a for loop.
A for loop consists of up to three statements inside the parentheses immediately following the keyword for, as well as a body of statement(s) enclosed in curly braces ({ }).
  1. The first statement is an assigment statement that declares a variable that will serve as an index for the array. Most commonly you'll see the statement var i = 0; in this position. This statement is executed only the first time we enter the loop.
  2. The second statement contains a boolean expression that tests whether the loop should continue to be executed. This is evaluated in every iteration. In the moment that the expression evaluates to false, the loop is ended.
  3. The third statement updates the index variable, so that the loop can eventually end after a certain number of iterations. Failing to update the index variable, will put the program in a state of an endless loop which will eventually crash the browser.

This is how to explain a for loop in plain English: for as long as the test condition is true, keep repeating the code inside the body of the loop. This is what happens in every step of the loop in the example with the book titles.

A common visualization of a for loop is a flowchart like the following. You can see how the index assignment comes before the loop, the condition statement (actually a boolean expression) determines whether to start loop and to continue looping, and the update statement comes at the end of the loop to set things up for the next test of the condition. Here's the flowchart:

flowchart of a for loop

Flowchart of a for loop

Let's walk through the preceding particular example of a loop in great detail:

Index value
before test
i < books.length
Enter loop? array[index] Index value
after update
0 0 < 4 yes books[0] 1
1 1 < 4 yes books[1] 2
2 2 < 4 yes books[2] 3
3 3 < 4 yes books[3] 4
4 4 < 4 no

for loops are one of the most important programming constructs in every programming language. Understanding how to write and use them properly will make you a better programmer.

Loops over Lists of Objects

So far, we've seen lists (arrays) of numbers and strings. Let's look at lists that contain objects, since objects can have more interesting stuff in them. This is really just a combination of two things you already have some understanding of:

  • objects, which are collections of propeties and their corresponding values. The values can be accessed by the name of the property.
  • lists, which are collections of things. The list elements can be accessed by their index.

We'll do this by way of an example. In the book list above, we had two matching lists of equal length, so that books[i] is the title and prices[i] is the corresponding price. If these two lists got out of sync, the price wouldn't match the object, and everything would be messed up in a way that would be hard to fix if there were thousands of books.

A better way to structure the data is a single list of objects, where each object describes a book. (Imagine pulling this data out of a spreadsheet or database.) Here's the example:

var books = [{title: "Mockingjay", author: "Suzanne Collins", price: "$4.99", year: 2010},
             {title: "Fahrenheit 451", author: "Ray Bradbury", price: "$2.99", year: 1953},
             {title: "Persuasion", author: "Jane Austen", price: "$1.99", year: 1818},
             {title: "Middlemarch", author: "George Eliot", price: "$0.99", year: 1874}

Now, suppose we want to put that data on the page, with some surrounding HTML for formatting and such. The pattern might look like this:

<span class="title"></span> by <span class="author"></span>. 
First published in <span class="year"></span>. Current price: <span class="price"></span>

Our strategy is to loop over all the books, and for each book, do the following:

  1. create a new P element.
  2. set the innerHTML of the element to the code above.
  3. copy the values out of the object and into the corresponding spans, using the class name as a CSS-style query selector.

Here's the code, as an exercise:

Exercise 4: Dynamic HTML with Arrays and Lists of Objects

Here's a step-by-step explanation:

  • Step 1 creates the list of objects describing each book
  • Step 2 gets the element on the page that we're going to append these to
  • Step 3 sets a string literal containing our HTML template
  • Step 4 is our loop control structure
  • Step 5 creates an empty paragraph, currently not attached to the document
  • Step 6 sets the innerHTML of the paragraph, creating the desired elements
  • Step 7 gets the current element of the list
  • Step 8 sets all the span contents from the corresponding object properties
  • Step 9 attaches the paragraph to the document

You can see how this might be used to format data coming from the server, such as a Facebook update, the arrival of some new mail from Gmail, and so forth. Loops over lists of objects is a general and powerful technique.

for loops for Object Properties

This section is considered advanced material, and we will not be using it this semester. Reading it is entirely optional. However, it's here for the interested reader.

The four assignment statements in the previous example can be replaced by a more general and abstract mechanism that allows us to loop over the properties of an object. JavaScript provides a special variant of the loop statement to do exactly that.

How would we create our books page using this special loop? We will use a for loop to iterate through all the books in the array and another for loop to iterate through the properties of every book object. These two for loops have slightly different syntax, to reflect the fact that one works with an array and the other with properties of an object.

We will again show the code that generates the page and then discuss the special for syntax for objects. Click on the "Execute it" button to see the results in the blue-bordered box.

Exercise 5: Dynamic HTML with Arrays, Objects and nested loops

Although this example has twice the amount of data from the one that used arrays, the number of code lines we had to write is almost the same. Here is an explanation of very line:

  • Line 1 declares the array books that stores a list of book objects.
  • Line 2 declares the variable divElementthat will refer to the div element in the HTML page where the book entries will be displayed.
  • Line 3 declares the variable oneBook that contains the HTML template af a line that will display the book information. Notice that we are using four <span> elements with class names, in order to allow for their styling with CSS. But all these span elements have no text, it will be added through our code.
  • Line 4 is the statement that declares a for loop that will iterate over all items in the array books.
  • Line 5 creates a new HTML element for the tag p. This will be used to store display every book line.
  • Line 6 sets the innerHTML property of the newly created p to the desired template.
  • Line 7 declares the variable book that stores one book object at a time.
  • Line 8 is the for statement that will iterate over all property names of a book object.
  • Line 9 is an assignment statement. On the right side, book[propName] will be evaluated to the property values such as "Mockingjay", etc. The left side refers to the span element that will display as content such values. For example: p.querySelector(".title").innerHTML. In order for this "trick" to work, we have to ensure that the class names for the span elements are the same as the properties of the book objects. This way, they can be created by concatening "." + propName.
  • Line 10 appends every created (and populated with information) p element to the container that will display all the books.

Notice in line 8 the new syntax of the for loop. It is much simpler than the one we saw for iterating over elements of an array. In English we can read for (var propName in book) {// statement(s);} like this: for every property name in the book object, store the name in the variable propName, and then execute the body of the loop.

Below is an example that shows a loop for only one of the book objects:

var book = {title: "Mockingjay", author: "Suzanne Collins", price: "$4.99", year: 2010};
for (var propName in book){
        console.log("property name is: " + propName + ". Its value is: " + book[propName]);

If you copy these lines in the console, you'll see the following result:

for loop for object properties
Using a for loop to iterate through properties of an object.

Important: Two ways to access values of properties

In the examples of this lecture we saw two different ways to access the values of object properties:

  1. Using the . notation, as in: person.firstName.
  2. Using the [] operator, as in book[propName].
Both of them return the value stored in that property but they cannot be used interchangeably. For example, we cannot write person[firstName] or book.propName. In the first case, Javascript will complain of a ReferenceError, in the second case it will not complain but it will return undefined, instead of the value. Therefore, remember these rules when accessing properties:
  • Use the . notation when you are directly referring to a property by its name. For example: book.year, person.firstName.
  • Use the [] operator when you are using a variable that was assigned the name of the property. For example, book[propName].