Arrays



Arrays



Now you know the fundamentals of JavaScript. You’ve created variables and functions, you’ve used if statements to conditionally take different actions in your code, and you’ve used for loops to repeat code multiple times.

This tutorial introduces arrays, which let you store multiple values in a single variable. This makes it easier to work with data and groups of items.


Multiple Variables

By now you’ve seen variables, which let you store a single:

let favoriteAnimal = 'cat';

document.write('My favorite animal is: ' + cat);

But what happens if you want to store multiple values? You have to create multiple variables:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

This becomes unwieldy pretty quickly. Whenever you want to add an animal to your zoo, you have to add a new variable, and then add code that uses that variable.

This is where arrays come in handy!

Arrays

Remember that values can be of different types. So far you’ve seen strings, numbers, and booleans. Arrays are a new type, and they let you store multiple values.

To create an array, start with [ ] square brackets, and then inside those square brackets, add a comma-separated list of values:

let animals = ['lions', 'tigers', 'bears'];

After you create an array, you can access the values inside of it by index using [] square brackets and then a number:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Note: Array indexes start at 0. So the first value is at index 0, the second value is at index 1, the third value is at index 2, etc.

For Loops

Now the animals array stores multiple values, but the HTML still references each value one at a time. This isn’t much of an improvement, because if you add an animal to the array, you still need to write code that adds it to the page.

Remember that for loops let you repeat code multiple times. You can combine for loops and arrays to repeat the same code for multiple values:

for(let i = 0; i < animals.length; i++) {
  document.write('<li>' + animals[i] + '</li>');
}

This code creates a for loop that loops from 0 to animals.length (which is a special variable that arrays give you). Inside the body of the loop, the code writes the value at that index to the page.

Now you no longer have to write code for each value in the array- the for loop takes care of it for you!

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Try modifying this code so the zoo contains 10 different animals. Notice that you only need to change what’s in the array, not the code that processes it.

For Of Loops

The pattern of using a for loop to do something with every value in an array is so common that there’s now a shortcut for it called the for of loop. It looks like this:

for(let animal of animals) {
  document.write('<li>' + animal + '</li>');
}

This syntax lets you avoid creating a loop variable like i or index, and automatically loops over the array for you.

Getting Arrays

The code above creates an array using the [ ] square bracket syntax. You can also get an array from various functions. Here are some examples:

Getting Elements

Remember that the document.getElementById() takes an ID as a parameter and returns the element with that ID:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Similarly, the document.getElementsByTagName() function takes an HTML tag name (like h1 or p) and returns an array containing every element with that tag. Then you can loop over the array and modify every element. Here’s an example:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

The document.getElementsByClassName() is similar, except it takes a CSS class name instead.

Splitting Strings

You’ve seen string values that contain text, like this:

let message = 'the quick brown fox jumps over the lazy dog';

You can use the split() function to separate a string into individual parts. The split() function takes a regular expression, which is a pattern to use as a delimiter. Here’s some code that splits a string on spaces, which returns an array containing each individual word in the string:

let wordsArray = message.split(/\s+/);

Putting it all together, it looks like this:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

These are two examples of functions that return an array, but there are many more. But the idea is the same: you call a function to get an array, and then you can loop over the values in it.

Array Functions

In addition to looping over the values in an array, you can also call functions on an array to modify it. Here are some examples:

Adding Values

The push() function adds a value to an array:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Removing Values

The splice() function removes a value from an array. It takes two arguments: an index and a count.

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Sorting Arrays

The sort() function rearranges the values in your array so they’re in order.

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

These are a few examples of functions that you can use after you have an array, but there are many more. Check out W3Schools and MDN for more information.

Data Processing

Arrays and for loops are used for many things. Anytime you have repeated data, like a list of messages, or posts, or images, you’re probably using an array and a for loop. Another common usage of arrays and for loops is data processing. Here are a few examples:

Conditional Output

Let’s say you have an array of words, and you want to output the words that start with the letter K. You can put an if statement inside your loop to do that:

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Calculating the Maximum

Let’s say you have an array of words, and you want to find the longest. You can use a combination of variables, for loops, and if statements to find it.

Code Editor ?

See the Pen by Happy Coding (@KevinWorkman) on CodePen.

Finding the minimum is very similar!

These are two specific examples, but my real goal was to show the general pattern of using a for loop along with the other concepts you’ve learned. A big part of coding is figuring out the right combination of things to use to accomplish your goal!

Homework

  • Create a webpage where users can enter a list of their favorite animals. Show the animals as an alphabetized list.
  • Create a string that holds the lyrics to your favorite song. Then output the words in alphabetical order, the longest word, the shortest word, and all words that start with the first letter of your name.

Comments

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!