Day 2: Collection Types
Lesson 1: Arrays
So far we have looked at storing individual bits of data in
You may have already thought about this next problem, what if we want to store a series of variables or constants?
We could do this:
1let personAgeOne = 24; 2let personAgeTwo = 12; 3let personAgeThree = 78; 4let personAgeFour = 37;
But what if we want our application to work with more than four people? We can't just declare
This is where arrays come in, they let us store any number of items.
Let's build up an example:
You can see in the example above with
So, what about the arrays in arrays method that I mentioned?
To get this to appear in the playground you'll need to click on the little triangle on the left hand side of each line. When you click that you'll see that you have an array with two elements in it. These elements are arrays, one with 4 names in it and one with 4 numbers in it.
Notice also how I was able to use a variable name in the array creation with
What about if you want to access an element in an array? Well we do that by using the elements location number, or index with this syntax
ages[index]. Like this:
Note something interesting. To get the first element (24) I've written
ages, and to get the last item it's
As a consequence the last item in the array is always the
arrays length - 1. In fact we can see that below:
 syntax also lets you change an element's value:
Arrays are the most commonly used collection data type in all of programming, they feel overwhelming to begin with, but with extended use they become second nature.
More on arrays later.