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.
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".
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 arrayfor
loops for ArraysImagine 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> ... </div>
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.
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.
books
that stores a list of book titles.prices
that stores the corresponding prices for each book.
These two arrays have the same length.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;
.oneLine
the string value created by
concatenating together some HTML tags and their text values from the two arrays of data.html
.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 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 ({ }
).
var i = 0;
in this position. This statement is executed only the first time we enter the loop.false
, the loop is ended.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:
Let's walk through the preceding particular example of a loop in great detail:
Index value before test |
Condition 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.
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:
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:
P
element.
innerHTML
of the element to the code above.
Here's the code, as an exercise:
Here's a step-by-step explanation:
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 PropertiesThis 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.
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:
books
that stores a list of book objects.divElement
that will refer to the
div element in the HTML page where the book entries will be displayed.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.for
loop that will iterate over
all items in the array books
.p
. This will be used to store
display every book line.innerHTML
property of the newly created p
to the desired template.book
that stores one book object at a time.for
statement that will iterate over all property names
of a book object.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
.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:
In the examples of this lecture we saw two different ways to access the values of object properties:
.
notation, as in: person.firstName
.[]
operator, as in book[propName]
.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:
.
notation when you are directly referring to a property
by its name. For example: book.year
, person.firstName
.[]
operator when you are using a variable that was assigned
the name of the property. For example, book[propName]
.