# 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.&#x20;

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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learning.pavey.dev/javascript/js-basics/arrays.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
