for-loops

Learn how to repeat a set of code as many times as you like, without using functions. For-loops are a fundamental part of every programming language. We'll see how to write them and how to use them with arrays.

Loops are a new concept. They’re very powerful. They’re used to run a piece of code more than once so that we don’t have to write the same code over and over. They have different use cases than functions.

Let’s say we want to use console.log() ten times. We could write ten different statements, or we could use a loop.

for-loops

For-loops follow a format which might seem daunting at first. Try to get through it.

We start a for-loop by writing the reserved keyword for, with parentheses after it.

for()

Inside the loop, we need to put three pieces of information. This information will tell the loop how many times it should run and what it’ll do after each run.

for(/*first item*/; /*second item*/; /*third item*/)

We’re trying to print something ten times, so we somehow need to tell our loop to run ten times. Let’s see how to do that.

We’ll discuss the first piece of information, then the last, then the second.

Declare a Variable

Inside the parentheses, we first want to declare a variable. This will happen once, before the loop runs.

for(let index = 0; /*second item*/; /*third item*/)

Increase the Variable

At the end of the loop, we want to write something that will happen after every run of the loop. In our case, we want to increase index by one. So every time the loop runs, index gets increased by one.

for(let index = 0; /*second item*/; index = index + 1)

Condition

In the middle, we want to set a condition. The loop will run over and over until this condition becomes false. In our example, we want to run this loop ten times.

We have an index that starts at 0 and goes up by one every time the loop runs. We want to tell the loop to stop when index is equal to ten.

for(let index = 0; index < 10; index = index + 1)

Loop Body

We have our for-loop’s backbone. This loop will run ten times and then stop. At the moment, it does nothing. We need to give this loop a body. We do this with the {} characters placed after the parentheses, just like in functions.

The code we write inside {} will run every time the loop runs.

for(let index = 0; index < 10; index = index + 1) {
    // loop body
}

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy