Calling Array Functions - JavaScript Basics - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART I JavaScript Basics

LESSON 7 Calling Array Functions

image

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

To make arrays even more powerful, JavaScript comes ready-made with a selection of handy functions and statements for accessing and manipulating arrays. For example, you can join arrays together, push new items into an array (and pop them off again later), reverse the data in an array, sort it alphabetically or numerically, and more.

Therefore, in this and the following couple of lessons, we’ll look at these functions and how to use them.

Using for(… in …)

The first feature I’d like to introduce is for(… in …), because with it you can iterate through an array one element at a time, which we will need to do in the following examples in order to see the results. To show how this iteration works, let’s start with a simple array of cat types:

image

Now, let’s use for(… in …) to display all its elements, as follows (resulting in Figure 7-1):

image

image

FIGURE 7-1 The contents of Cats is displayed.

What’s happening here is the for() keyword creates a new variable called index, which it initializes with the integer value of 0, so that it points to the first element in the array specified (in this case Cats[]).

Then the contents of the curly braces are executed once for each element in the Cats[] array, with index being incremented each time around. Therefore, the first time element 0 is indexed by index, the second time, it is element 1, and so on until there are no more elements left in the array to process.

For reasons I explain in Lesson 10, the curly braces can be omitted when there is only a single statement to be executed by such a for() loop. Therefore, for the sake of simplicity in the following examples, I will reduce this type of code to the much shorter example (which also uses the index variable i instead of index but is equally valid syntax):

for (i in Cats) document.write(Cats[i] + ′<br>′)

Now that there’s an easy way to display the contents of an array, we can start to look at the array functions provided by JavaScript and see how to use them. You can try this example yourself by loading the for_in.htm example from the companion archive into your browser.

Using concat()

Using the concat() function, you can return a new array created by joining two other arrays together. The two original arrays are not changed in any way by this function; only the result of joining them together is returned.

To see how this works, let’s create a second array to go with the Cats[] array created a little earlier, as follows:

image

With both arrays now created, we can run the concat() function on them, like this:

Pets = Cats.concat(Dogs)

And now to see the result of this operation, we can issue the following statement:

for (i in Pets) document.write(Pets[i] + ′<br>′)

The code to create these two arrays and the preceding pair of statements are in the concat.htm file in the companion archive. As you can see in Figure 7-2, the result is that the new array Pets[] now contains all elements from both the Cats[] and Dogs[] arrays, in order.

image

FIGURE 7-2 The two arrays have been concatenated.

For a similar result, but with the contents of the Dogs[] array before the Cats[], you could have issued this statement:

Pets = Dogs.concat(Cats)

In fact, you could omit the creation of the Pets[] array altogether and simply iterate through the result of the concat() call, like this:

image

image

Although it works, the preceding is wasteful code because the concat() function has ended up being used twice and called multiple times in the loop. Because the result of the concatenation is lost once you have accessed it, this isn’t recommended coding practice. However, this code illustrates that by placing square brackets containing an index variable after the call to concat() (namely[i]), you can index into the array returned by the call.

An Alternative to concat()

If all you want to do is quickly see what values are in an array, you can use the implied concatenation you get when referencing an array as an argument to the document.write() function. For example, you can list all the elements in the Dogs[] array to the browser (separated with commas), like this:

document.write(Dogs)

Note how you must omit the [] characters from after the array name in order for this to work, and the result of this statement will then be like the following:

Pit Bull,Spaniel,Terrier,Beagle,Shepherd,Bulldog

Using join()

Sometimes you may wish to turn all the elements in an array into a string, and this is easy to do using the join() function. For example, let’s take the following case of the Cats[] array:

document.write(Cats.join(’ and ’))

This statement calls the join() function, passing it the string ′ and ′, which is used as a separator, which is inserted between each element, as shown in Figure 7-3.

image

FIGURE 7-3 The result of joining array elements into a string

You may use any string as the element separator, or none at all, as in the following three examples (with extra spaces inserted to clearly show what’s going on):

image

When no argument is passed to join(), a comma is assumed as the separator, whereas to have no separator, you should supply an empty string (′′). Therefore, in turn, the three previous statements display the following:

Long Hair, Short Hair, Dwarf, Farm, Tabby, Tortoiseshell
Long HairShort HairDwarfFarmTabbyTortoiseshell
Long Hair,Short Hair,Dwarf,Farm,Tabby,Tortoiseshell

The forEach() Function

An alternative to using for(… in …) is the forEach() function. With it, you can iterate through an array of elements very easily, as follows (where v in the arguments of the Info() function is the value of each element, i is the index of the element, and a is the array being traversed, which isDogs[] in this case):

image

As shown in Figure 7-4, the Info() function simply displays information about each element in the array. The powerful thing is that the forEach() function name is simply attached to the Dogs[] array name with a period operator, and (without needing any loops) the array gets processed by the Info() function, which has been passed as the argument to forEach().

image

FIGURE 7-4 Iterating through an array with forEach()

The map() Function

One very quick and easy way to process all the elements in an array is to pass each element in the array to a function via JavaScript’s map() function. For example, the following code creates an array populated with numbers, and then applies the Math.sqrt() function to each element, returning the results in the new array Roots[], all via a single call to the map() function.

image

You can see the result of running this code (maps.htm in the companion archive) in Figure 7-5.

image

FIGURE 7-5 Applying the map() function to an array

Summary

In this lesson you have learned how to process arrays to extract data from them in loops, how to apply a function to them and to individual elements, and how to join arrays together. Therefore, now you will be able to use arrays for complex data storage and manipulation. In the following lesson we’ll look at how you can also use arrays for temporary data storage in the form of stacks to support advanced techniques such as recursion.

Self-Test Questions

Using these questions, test how much you have learned in this lesson 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. How can you use the for(… in …) function to iterate through an array one element at a time?

2. Which function is similar to using for(… in …), but can be implemented with a single instruction?

3. With which function can you join two arrays together into a single array?

4. What single line of code would you use to join together two arrays called tennis[] and golf[] into a third called sports[]?

5. How can you quickly pass an entire array of elements to a function?

6. With a single line of code, how can you easily invoke a function on each element of an array and return a new array containing the processed element values?

7. What is the join() function used for?

8. What single line of code would you use to display all the elements in the array sports[] as a string, with each separated from the next by the string ′ plus ′?

9. If you have an array of hobby names called hobbies, what does the command document.write(hobbies) do?

10. What does the command activities = sports.concat(hobbies) do?