Creating JavaScript Arrays - JavaScript Basics - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART I JavaScript Basics

LESSON 5 Creating JavaScript Arrays

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

JavaScript is capable of managing data in a more powerful manner than simply via variables. One example of this is JavaScript arrays, which you can think of as collections of variables grouped together. For example, a good metaphor for an array might be a filing cabinet with each drawer representing a different variable, as shown in Figure 5-1.

image

FIGURE 5-1 A filing cabinet representing a 10-element array

As with the small pot metaphor in Lesson 2, using a filing cabinet to assign a value, you should imagine writing it down on pieces of paper, placing it in the relevant drawer, and closing it. To read back a value, you open the drawer, take out the paper, read its value, return the paper, and close the drawer. The only difference between the cabinet and the pots is that the drawers of the filing cabinet (representing an array) are all in sequential order, whereas a collection of pots (representing variables) are stored in no particular order.

Although JavaScript arrays can be any size (up to the maximum allowed by the JavaScript engine), for the sake of simplicity I have only shown 10 elements in the figure. You can access each of the elements in an array numerically, starting with element 0 (the top drawer of the cabinet). This index number is important, because you might think that logically the number 1 would be the best starting point, but that isn’t how JavaScript arrays are accessed—you should always remember that the first element is the zeroth.

Array Names

The rules for naming arrays are exactly the same as those for naming variables. Array names must begin with either an upper- (A-Z) or lowercase letter (a-z), or the $ or _ symbol. No other character may begin an array name (except for some Unicode characters, but these should generally never be used in variable names).

Array names may not contain any mathematical operators (such as + or *), punctuation (such as ! or &), or spaces, but after the first character, they may include the digits 0-9 or any of the characters that can begin an array or variable name.

All JavaScript keywords (such as window, open, string, and so on) are reserved and may not be used as array names.

Creating an Array

To create an array, you can declare it in advance, like this:

MyArray = new Array()

This has the effect of creating a new object of the type Array() and then calling it MyArray. This array object contains no data, but is ready for data to be assigned to its elements.

Creating an Array of a Specific Length

To create an array of a specific length, you provide a single argument to the Array() function call, like this:

MyArray = new Array(5)

This has the effect of creating a new object of the type Array(), which contains no data, but has five elements ready to be populated with values.

Assigning Values to an Array Element

You can populate arrays with data (in a similar manner to assigning values to variables) like this:

image

Here the integer 23 is assigned to element 0 (the top drawer of the cabinet), whereas the floating point number 67.35 is assigned to the element at index 1 (the second drawer down because indexes begin at 0). In fact, you can assign any legal value to an array element, including strings, objects, and even other arrays (which I come to in Lesson 6), like this:

image

image

I explain the use of objects in Lesson 13, but for now, all you need to know is that MyArray[4] now contains a Date object holding the current date and time.

You are not restricted to assigning values in order, so you can go right in and assign values to any elements, like this:

image

In this instance, if the length of MyArray[] was previously less than nine elements, its length will automatically be increased to nine by the former of these two assignments.

Using Indexes

The element number used for storing a particular value is known as the array index, and you can use integer values (as shown so far) or variable values as indexes. For example, the following first creates a variable and assigns it a numeric value, which is then used to assign another value to the array:

image

This has the effect of assigning the string value ″Good evening″ to the element with an index of 123 in MyArray[].

Retrieving Values

Once an array has been created and it has been populated with data, to retrieve a value from an array, you simply refer to it, like this:

document.write(MyArray[0])

This will fetch the value stored in the zeroth element of MyArray[] (or the top drawer of the filing cabinet metaphor) and then pass it to the document.write() function to display it in the browser. Likewise, you can return a value using a variable, like this:

image

Whatever value is stored in element 713 of the array will then be displayed in the browser.

image

The preceding two examples (and many following ones) assume you have already created an array. If you have not previously created an array but try to read from one, an error will be generated and your code will fail.

There are other ways you can use array values, such as assigning them to other variables or other array elements, or using them in expressions. For example, the following code assigns the value 23 to an array element, which is then looked up and used in an expression, in which 50 is added to it and the result (73) is displayed in the browser:

image

Or, you may wish to display a value in an alert window using code such as the following, which results in your browser looking like Figure 5-2 (although the style of the window varies by browser):

image

image

FIGURE 5-2 Displaying a value in an alert window

Using Array Elements as Indexes

You can even go a step further and use the value stored in an array element as an index into another (or the same) array, like this:

image

Here the zeroth element of OtherArray[] is assigned the integer value of 77. Once assigned, this element is used as the index into MyArray[] (rather like the movie Inception, with arrays within arrays). However, this is quite complex programming, and you are unlikely to use these types of indexes as a beginner to JavaScript.

image

The fact that you can use any valid integer value (including values in variables, array elements, and those returned by functions) means that you can use mathematical equations to iterate through arrays. For example, as you will discover in Lesson 11, it is easy to create code that runs in a loop to process each element of an array in turn.

Other Ways of Creating Arrays

You have already seen the following type of declaration for creating a JavaScript array:

MyArray = new Array()

But there are also a couple of other methods you can use, which also have the effect of simplifying your code by allowing you to populate the array with some data at the same time. The first method is as follows:

MyArray = new Array(123, ″Hello there″, 3.21)

Here the array MyArray[] is created and its first three elements immediately populated with three different values: an integer, a string, and a floating point number. This is equivalent to the following (much longer) code:

image

You can also go a step further and simplify things right down to their bare bones by using code that implies the creating of an array, without using the new keyword or the Array() function, like this:

MyArray = [123, ″Hello there″, 3.21]

image

Once you have created an array, if you need to apply any more values to elements within it, you must use the standard form of assigning values. If you reuse the short form of combined array creation and value assignment, it will simply reset the array to the values in the assignment.

Using Associative Arrays

Using numeric indexes is all well and good when you only have a few elements in an array to cope with. But once an array starts to hold meaningful amounts of data, using numbers to access its elements can be highly confusing. Thankfully, JavaScript provides a great solution to this by supporting the use of names to associate with array elements, in much the same way that variables have names.

Let’s use JavaScript’s associative arrays to store the ages of the players in a mixed, under eleven, five-a-side soccer team. Here the array is initialized and then the age of each player is assigned to an element in the array using the players’ names:

image

Having been assigned, these values they can now easily be looked up by name, like this, which displays Cathy’s age in the browser:

document.write(SoccerTeam[′Cathy′])

Keys, Values, and Hash Tables

When you use associative arrays, you are actually creating a collection of key and value pairs. The name you assign to an array element is known as the key, whereas the value you provide to the element is the value.

In other languages (such as PHP), this type of data structure is implemented using a hash table. When an object (such as a string) is used as a key for a value, this is called a hash value and the data structure is a hash table. In Lesson 13, you will learn how all variables in JavaScript are, in fact, objects and that you can access them in a variety of ways, as well as those that have been shown so far (variables, arrays, and associative arrays).

Other Ways of Creating an Associative Array

If you wish, you can use a short from of creating and populating an associative array, like this:

image

image

The syntax here is different from populating a standard array, in that you must enclose the element value assignments in curly braces. If you use the square brackets instead, the statement will fail. Also, rather than using = you use the : operator to assign values.

In fact, you can shorten the syntax even further by having your code imply the new keyword and Array() function, like this:

image

I’m sure you’ll agree this is much simpler and easier to use, once you know that this type of code structure causes the creation of an array. But you may prefer to stick with the longer form until you are completely happy with using arrays. Also, I have chosen to be liberal with newlines here for reasons of clarity, but if you wish, you can run all these five substatements into a single line.

As with standard variables and arrays, you are not restricted to only storing numbers in associative arrays, because you can assign any valid value, including integers, floating point numbers, strings, and even other arrays and objects. The following illustrates a couple of these:

image

In the preceding example both strings and numbers have been assigned to the array elements. You can read back any value simply by referring to it, like this, which displays the value in Occupation (namely Philanthropist) in the browser:

document.write(MyInfo[′Occupation′])

image

In Lesson13 you will learn how JavaScript arrays are actually examples of objects (as are all JavaScript variables) and how they can be used in Object-Oriented Programming (OOP).

Summary

By now you should have a pretty good understanding of JavaScript arrays and should begin to see how they can make excellent structures for handling your data. In the following lesson I’ll show you how there’s actually a lot more to arrays than you’ve seen so far, and we’ll begin to make some reasonably complex data objects.

Self-Test Questions

Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. Which characters are allowed as the first in an array name?

2. Which characters are allowed in the body of array names?

3. How would you create a new array called mydata?

4. How would you limit this new array to, for example, 20 elements?

5. How would you reference item 11 in the array mydata?

6. Is the first item in an array at index 0 or 1?

7. How can you populate an array with data at the time of creation?

8. What is an associative array?

9. How would you add the key/value pair of Name/Alice as a new element in the associative array mydata?

10. How would you retrieve the value for the key Name in the associative array mydata?