Arrays are fundamental data structure in programs. They are one of the most used data types and allow for storing all sorts of information. Let's look at some examples.
const todos = ['Walk the dog', 'Clean my room', 'Take out the trash'];
const salaries = [15000, 20000, 40000];
const todosAndSalaries = ['Walk the dog', 15000];
This is a simple example. In the first variable we stored a list of strings in a variable called todos. Then, we saw how we can store a list of numbers in a variable called salaries. The last variable shows how we can mix types and store them both in a list.
Okay, now that we created an array, how do we get the items out of the array.
const todos = ['Walk the dog', 'Clean my room', 'Take out the trash'];
console.log(todos[0]); // prints Walk the dog
console.log(todos[1]); // prints Clean my room
console.log(todos[2]); // prints Take out the trash
We can access items in the array by using the []
brackets and putting the index of the item inside. Note that in programming, we start at 0 and note 1.
So in our example, you can see that we access each item by the index and the brackets. In the first console.log we access the first item in the todo by todos[0]
which says: give me the first item in my list.
Now that we have arrays created, how we can add more items? We could recreate the array, but that would be a pain.
const todos = ['Walk the dog', 'Clean my room', 'Take out the trash'];
todos.push('Pay rent');
console.log(todos[3]); // prints Pay rent
We can use the push
method to add a new item to our array. What if we want to add the item to the front?
const todos = ['Walk the dog', 'Clean my room', 'Take out the trash'];
todos.unshift('Pay rent');
console.log(todos[0]); // prints Pay rent
Here we used the unshift
method to add an item to the front of the array. There are many more methods on arrays that we will explore in the future.
A common task you will want to do when using arrays is to get the size of an array. We can do this with the length property.
const todos = ['Walk the dog', 'Clean my room', 'Take out the trash'];
console.log(todos.length); // prints 3
If you haven't learned loops yet, don't worry, we cover them later. However, ne of the most common tasks you will perform is looping over an array of items. Let's see how to do that.
const todos = ['Walk the dog', 'Clean my room', 'Take out the trash'];
for (const todo of todos) {
console.log(todo);
}
Here we are saying, for each item in our todos list, store that item in a variable called todo. Then, we print out the todo. Don't worry too much if this doesn't make sense. We have an article just for loops.