Arrays

The Array Type

This reading will be about one of JavaScript's global objects, the Array type. JavaScript arrays are used to store multiple values all within a single structure, much like a creating a list (like a shopping list). Arrays can hold strings, integers and even other arrays! Arrays are incredibly useful for holding a bunch of different information all in one place.

When you finish this reading, you should be able to:

Using arrays

While coding you will often find yourself needing to refer to a bunch of data at once. For instance, what if you wanted to refer to the entire English alphabet. Sure, you could create a bunch variables for each letter in the alphabet:

        
let a = "a";
let b = "b";
let c = "c";
let d = "d";
// and so on for way too long...
        
    

However this becomes cumbersome and unmanageable quickly. An Array is a data structure that solves this problem. Arrays are always wrapped in square brackets, [], and store their comma-separated values in sequential order. Arrays in JavaScript are also very flexible: you can put elements into an array, replace elements in an array, and remove elements from the array.

So going back to the first example of containing the alphabet:

        
let alphabet = [
  "a", "b", "c", "d", "e", "f",
  "g", "h", "i", "j", "k", "l",
  "m", "n", "o", "p", "q", "r",
  "s", "t", "u", "v", "w", "x",
  "y", "z"
];
        
    

Now you can just use one variable to access any letter of the alphabet!

Indexing arrays

Calculating the length of an array

Since an array can contain any number of values you will find it useful to count the number of values available to you using the .length property on an array. Simply chain a .length to the end of an array:

        
console.log([4, 7, 9].length); // => 3
console.log([1, 2].length);    // => 2
console.log([].length);        // => 0
        
    

Properly indexing an array

Arrays consist of multiple values all stored in sequential order. These values are numbered by indices starting at 0 (just like indexing a string!). So given the below example:

        
let numbersAndLetters = ["b", "z", 17, "cat"];
        
    

In the above numbersAndLetters array if you access numbersAndLetters at the index of 0 you get back the value of "b". If you access numbersAndLetters at the index of 1 you get "z", at the index of 2 you get 17, etc. You can specify which value you'd like to access in an array by using square brackets,[], and specifying an index:

        
console.log(numbersAndLetters[0]); // => "b"
console.log(numbersAndLetters[1]); // => "z"
console.log(numbersAndLetters[2]); // => 17
console.log(numbersAndLetters[3]); // => "cat"
        
    

Notice that even though the index at numbersAndLetters[3] has the value of a string with multiple characters ("cat"), you return the entire value listed at that index.

Reminder: Arrays always start at the index of 0, not 1. This is the convention in programming. Additionally, indices should always be a number.

You can access a value in an array directly by providing an index for the value you'd like to access in that array (array[index]). See below for an example:

        
console.log(["a", "b", "c"][0]);   // => "a"
console.log(["a", "b", "c"][1]);   // => "b"
console.log(["a", "b", "c"][2]);   // => "c"
console.log(["a", "b", "c"][3]);   // => undefined
console.log(["a", "b", "c"][-1]);  // => undefined
console.log(["a", "b", "c"][0.5]); // => undefined
        
    

As you see in the code above, if you try to access an element at an index that is not inside the array, you get back undefined. This makes sense because there is no value at that given position!

The classic "off by one" error

Arrays are similar to strings in that both of their indices start at 0 instead of 1. Forgetting this fact can lead to some pretty confusing situations. Let's focus on an important distinction: the index of the last value of an array is always one less than its length.

        
let arr = [4, 7, 9];
console.log(arr.length);      // => 3
console.log(arr[arr.length]); // => undefined
console.log(arr[3]);          // => undefined
console.log(arr[2]);          // => 9
        
    

In other words, although the length of [4, 7, 9] is 3, the index of the last value (9) is 2. A good rule of thumb for accessing the last index of an array is to find the length and then subtract one:

        
let arr = [4, 7, 9];
let lastIndex = arr.length - 1; // => (3 - 1) = 2
console.log(arr[lastIndex]);    // => 9
        
    

Working with arrays

Containing data in arrays

By packaging groups of related data into a single array, you gain the added benefit of being able to refer to that data as a single collection. Arrays don't have to just hold single characters—they are capable of holding entire strings, numbers, and even other arrays!

        
let wackyArray = [2, 17, "apple", "cat", ["apple"]];

console.log(wackyArray[0]); // => 2
console.log(wackyArray[1]); // => 17
console.log(wackyArray[3]); // => "cat"
console.log(wackyArray[4]); // => ["apple"]
        
    

Just think of all the possibilities of what you can store in a single array! However, just because you can doesn't mean you should. In practice, you will almost always be storing similar kinds of data, that are coming from a common source (i.e. items in a shopping list, ID numbers, tasks on a todo list).

Replace elements in an array

To replace elements in an array, you can simply reassign the element at a specific index in the array.

For example, in an array of [1, 2, 3], you can replace 1 with 4 by reassigning the element of an array at the index of 0.

        
let arr = [1, 2, 3];
console.log(arr); // [1, 2, 1]
arr[0] = 4;
console.log(arr); // [4, 2, 1] // first element changed to 4
        
    

Note: Although you can index into strings very similarly to arrays, do not attempt to do this with strings! It will not work:

        
let str = 'hello';
console.log(str); // 'hello'
str[0] = 'j'; // DON'T DO THIS
console.log(str); // 'hello' // did not change
        
    

Using indexOf with arrays

You can also calculate the index of a given value within an array by using indexOf:

        
console.log([1, 3, 5, "apple", "jet"].indexOf(3));        // => 1
console.log([1, 3, 5, "apple", "jet"].indexOf(5));        // => 2
console.log([1, 3, 5, "apple", "jet"].indexOf("jet"));    // => 4

// this won't be found in the array
console.log([1, 3, 5, "apple", "jet"].indexOf("potato")); // => -1
        
    

If you attempt to search for a value that is not present in an array, indexOf will return -1. This makes sense because you know that -1 is not a valid array index. The smallest index possible is 0!

Concatenation with arrays

As a reminder, concatenation is just a fancy word for joining things together into a single collection. Now, this is where arrays will differ from strings. The + operator only exists for numbers and strings. If you try to use the + on an array it will try to help you out by converting your arrays into strings.

        
console.log("hel" + "lo");          // => hello
console.log([1, 2, 3] + [4, 5, 6]); // => 1,2,34,5,6
console.log("1, 2, 3" + "4, 5, 6"); // => 1,2,34,5,6
        
    

JavaScript was just trying to help! However that is probably not what you meant to do. Good thing JavaScript has a separate method for putting two arrays together. To concatenate arrays, you can use the aptly named .concat method:

        
console.log([1, 2, 3].concat([4, 5, 6])); // => [1, 2, 3, 4, 5, 6]
        
    

What you've learned