Arrays

An array is like a list. They are good for storing collections of data.

To define an array, we can use square brackets [] and place the values we want to include in between the brackets, separated by commas, like so [1, 2, 3, 4]

You do not need to include spaces after your commas, but they make things a bit more readable, so i like to include them. You can store any value inside an array, including objects and other arrays. This makes them very powerful for storing data. As with most types in JavaScript, arrays expose a number of builtin function we can use to manipulate the data stored inside them.

To call these builtin functions, we can access them like properties on the array.

Here are a few of the common ones.

forEach

The builtin forEach function will loop over every item in an array, and execute your provided function once for each item. The function will get the item as its first argument.

const animals = ['dog', 'cat', 'frog'];
animals.forEach(function(animal) {
console.log(animal);
});

In this example, we are passing in an anonymous function (because we haven't given it a name) and telling it it takes 1 argument (animal), because as we know, forEach will pass each item in the array into the function. We will now be able to access this item from the animal variable.

Working with arrays

If we have an array of names and we want to get (or replace a specific one) we can target a specific item in the array by using what is called bracket notation. consider the following:

var names = ['Scott', 'Christina', 'Joel'];
var joelName = names[2];
alert(joelName);

NOTE: remember, in programming the first number is always 0, so if you want the 3rd item, that is going to be number 2.

We can also add new items to an array by using the push method built in to the array, like so:

var animals = ['rabbits', 'cats', 'dogs'];
animals.push('chickens');
console.log(animals);

We say that an array is "iterable" because we can "iterate" over it with loops and functions.