> For the complete documentation index, see [llms.txt](https://learning.pavey.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learning.pavey.dev/javascript/js-basics/loops.md).

# Loops

A loop is a construct which lets us execute the same code multiple times with slightly different parameters each time.

There are two main types of loops.

### While Loop

These loops will run until a condition is no longer met. Be careful with this, as they can run forever!

```
var count = 0;
while(count < 10) {
    console.log(count);
    count = count + 1;
}
```

### For Loops

These loops will run a set number of times, according to the counter declared in the statement

```
for (var i = 0; i < 10; i = i + 1) {
    console.log(i);
}
```

#### 🤔 What is happening here?

> The statement (the bit in between the brackets) has 3 parts. those parts are separated by the semi colons `;`. The first part sets up the counter for the loop, the second part defines the condition for the loop to execute until, and the third part is responsible for iterating the counter at the end of each iteration.

We can use this to iterate through an array, too. for example:

```
var animals = ['Cats', 'Dogs', 'Geese'];

for(var i = 0; i < animals.length; i++) {
    var animal = animals[i];
    if (animal === 'Geese') {
        console.log('I do not love ' + animal);
    } else {
        console.log('I love ' + animal)
    }
}
```

##


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
