30 Days Of JavaScript

Day 2: Collection Types

Lesson 1: Arrays

So far we have looked at storing individual bits of data in var, let and const.

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 personAge... forever!

This is where arrays come in, they let us store any number of items.

The [ ] brackets are important, that's what tells JavaScript that you are creating an array, each element (number in this case) has to separated with a comma. You can store any data type in an array, numbers, strings, booleans ... even other arrays 🤯

Let's build up an example:

You can see in the example above with mixed that you can store multiple data types in an array. While it's very possible to do this it's not advisable and I can't think of a single time in my 15 years of using JavaScript when I've done it.

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 [names, ages]?

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[0], and to get the last item it's ages[3]. This is because, like most programming languages, JavaScript arrays are zero indexed. This means that the first element in an array is always the zero'th one.

As a consequence the last item in the array is always the arrays length - 1. In fact we can see that below:

This [] 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.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co