Arrays

A Word on Addressing Variables

We have seen variables already. We're about to expand the concept of variables a bit, but let us first look at where they reside while the program is executing, in the computer memory. The following is a fragment of that memory.

Figure 5.1. Fragment of the Computer Memory
Fragment of the Computer Memory

proj*/hello.js The illustration shows four variables. The types of the current values of these variables are four different types three of whom you already know. Let's assume they have been defined by:

'use strict';
let a = 42;         // a number
let var2 = true;    // a boolean
let x = "foo";      // a string

The string x may be considered a string of characters, an 'f', an 'o', and another 'o'. JavaScript allows us to focus specifically on any character in a string. The position of each character, it's index number is considered to be the distance of that character from the beginning of the string.

Strings have a length. This length is available to the programmer as a value of a standardly named variable, in our illustration: x.length that is the name of the string variable followed by a period followed by the word length. Because the positions are distances from the beginning of the string, the index of the first character is 0. Now because we start indexing with zero, the index of the last character is always the length of the string minus 1, in our example x.length - 1.

When it comes to strings we have a function to point out any character of a string given the index number.

'use strict';
let x = "foo";
console.log(x.charAt(0));               // f
console.log(x.charAt(x.length - 1));    // o (the last o)

Arrays

Figure 5.2. Fragment of the Computer Memory

(copied from previous section)

Fragment of the Computer Memory

With strings, life is easy, we always know what they consist of, characters of text. Sometimes it would be convenient in other contexts to group several values under one name. This phenomenon exists in JavaScript, and in other programming languages, because it is immensely practical, as we shall see. It is called an array. The illustration above has an array, counters.

The variable could have gotten its values through a process of tallying something, it could however also have been defines as you see it by

'use strict';
    let counters = [3, 0, 16, 1, 42, 7, 2, 1];

Just as the illustration hints, individual array elements are referenced through an index which, to our great surprise, is the distance of the element from the beginning of the array. Thus the first element is counters[0], and the last element is counters[counters.length - 1]. Notice that an array has a length attribute just as a string does. Notice also that indexes are delimited with square brackets in arrays.

Access to individual values of an array happens through use of indexes as in

'use strict';
    let counters = [3, 0, 16, 1, 42, 7, 2, 1];
    counters[3]++;          // 2
    counters[5] *= 2;       // 14
    console.log(counters);  // debugging print

Arrays are actually objects in JavaScript. Objects have properties as we shall see soon. They also have methods. Methods are functions associated with objects. In the concrete case let us see examples:

console.log(counters.length); // 8
    counters.push(63);  // method adds array element
    console.log(counters.length);   // 9

We saw above that an array is indexed with numbers starting from zero. Remember this by memorizing that an index is the distance from the beginning of the array to the element in question. Indexes may be given as variables as in

let i = 6;
console.log(counters[i]);   // 2
console.log(counters[Math.ceil(counters.length / 2)]);  // 42, The middle element

I mentioned that arrays exist because we need them. They allow, with the help of loops, easy and uniform processing of many values with a minimum of code. That shall be the topic of our next chapter. A sneak preview:

'use strict';
let counters = [3, 0, 16, 1, 42, 7, 2, 1];
let i = 0;
while (i < counters.length) {
    counters[i] *= 1.25;
    console.log(`value at index ${i} changed to ${counters[i]}`);
    i++;
}
console.log(counters);  // debugging print

Building Arrays

We have already seen a definition of an array. Let us se a couple of examples:

'use strict';
var arr1 = [];  // defines an empty array
console.log(arr1.length);   // 0

let arr2 = ['Abital', 'Bathsheba', 'Carmel', 'Delilah'];
console.log(arr2.length);   // 4
arr2.push('Ephrat');
console.log(arr2.length);   // 5
arr2[5] = 'Hagar';
console.log(arr2.length);   // 6
arr2[10] = 'Judith';
console.log(arr2.length);   // ?

let arr3 = new Array();
console.log(arr3.length);   // ?

let arr4 = new Array('Avi');
console.log(arr4[0]);
console.log(arr4.length);   // ?

Because of the usefulness of arrays you may frequently decide to use them dynamically for storing values that are dependent on user input, or as results of some process that you program is doing. Let us for example pretend that the users are encouraged to enter long words, and you need your program to store the words. If a word is already there, we will skip it.

'use strict';
let wordlist = ['object', 'array', 'number', 'variable'];
let word = prompt('Enter a good long word');
if (wordlist.indexOf(word) === -1 && word !== '') {     // if word not there and exists
    wordlist.push(word);    // push word onto array
    console.log('There are now ' + wordlist.length + ' words in the list');
} else {
    console.log('word already in list or nothing entered');
}

console.log(wordlist);      // debugging print
wordlist.sort();            // array method
console.log(wordlist);      // print again, see diff?

Methods on Arrays

We have seen that strings are a bit different from the other value types we encountered so far. They have properties and methods, re https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf . We have also pointed out that in some ways strings and arrays are similar. Arrays also have properties and methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array We have seen the length attribute in action already. We have seen the sort method and the push ditto in action. In an assignment, we encouraged you to look at the substring for strings. Do we have similar stuff on arrays?

Example 5.3. forEach
var fruits = ['Apple', 'Banana'];
fruits.forEach(function(item, index, array) {
    console.log(item, index);   // value and index of elements
    console.log(typeof array);  // keyword this could be used
});

In a sparse array only populated elements will be printed.

This function doesn't alter the array, but the callback function may do that.

There is no way to break out of this method. If you need that behaviour, you are referred to the normal loop constructs.


Example 5.4. every
function isBelowThreshold(currentValue) {
  return currentValue < 40;
}

var array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

Example 5.5. some
var array = [1, 2, 3, 4, 5];

var even = function(element) {
  // checks whether an element is even
  return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true

Example 5.6. slice
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

These were just some examples. Check the documentation for more. Whenever coding an oldfashioned loop to do some activity with an array, check to se if it doesn't already exist.