Learn
Lists
Lists: Putting it Together

Great! Now that you know all about lists, let’s write some code.

There are many ways to create lists and they can change depending on what language you are programming in. Here’s an example of a list in JavaScript that contains three items:

myList = ['apple', 'banana', 'pear']

In JavaScript, lists are created by defining a name for the list (such as myList), then setting it equal to a set of brackets []. If there’s nothing in between the brackets, the list is empty. But myList has three items in between brackets [], each separated by a comma ,:

  • 'apple'
  • 'banana'
  • 'pear'

You may have noticed that those were all strings. We can also put other data types in a list, including numbers and boolean values. We can even put other lists in a list!

To select an item from the list, we use the following syntax:

// the following line will return 'apple' myList[0]

Where myList is the name of the list we are selecting from and [0] is the first item in the list. As we may remember, the first item is at the 0th index. So this code would grab the string, 'apple'.

Let’s look at another example using the following list:

colors = ['red', 'yellow', 'green', 'blue']

To select the third item in the list, we would write colors[2]:

// the following line will return 'green' colors[2]

We could also save this selection to a variable, so we can use it later in our code:

// now myFavoriteColor is equal to 'green' myFavoriteColor = colors[2]

Instructions

First, create a list called comicStrip.

Save the following strings to comicStrip:

  • 'Codey sees the trail'
  • 'Codey starts the hike'
  • 'Codey is halfway'
  • 'Codey reaches the finish'

Run the code to see the comic strip!

Hint: make sure to separate each item with a comma: ,.

Select the 4th item from the list and save it to the variable selection.

Run the code. Did you select the correct frame? Try selecting other items in the list.

Hint: Remember that lists start at index 0!

Folder Icon

Take this course for free

Already have an account?