Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

for loop – JavaScript

Summary

To create a for loop in JavaScript, use the for keyword:

for (let i = 1; i < 10; i++) {
  // Insert code here
}

Details

A for loop lets you repeat a certain block of code multiple times (without having to copy and paste that block of code over and over again).

To start writing a for loop, use the for keyword followed by a pair of parentheses and curly braces:

for () {

}

Next, add a variable declaration inside the parentheses followed by a semicolon:

for (let i = 1;) {

}

This variable is used as a counter to keep track of how many times a pass through the loop has been performed. For a simple for loop, the variable name i is typically used. Next, add a condition followed by a semicolon:

for (let i = 1; i < 10;) {

}

This condition will be used to check the value of i after each pass through the loop. In this example, as long as the value of i is less than 10, the code inside the loop will be repeated. Finally, add a “final-expression” that will be used to change the value of i after each pass through the loop:

for (let i = 1; i < 10; i++) {

}

In this example, i++ is used. The two plus signs are called the increment operator. They increase the value of i by 1 after each pass through the loop.

There is also a decrement operator, which looks like this: --. You could use i-- to decrease the value of i by 1 after each pass through the loop (you’d want to make sure your condition in the middle makes sense, though).

Finally, the code you want to repeat goes inside the curly braces:

for (let i = 1; i < 10; i++) {
  console.log("hello world");
}

In the example above, the string “hello world” will print 9 times to the console.

Demo

Exercises

Try the following statements in the console:

for (let i = 0; i < 5; i++) {
  console.log('hello world');
}

You should see ‘hello world’ print out 5 times, or the phrase ‘hello world’ with a number 5 next to it.

References

for statement on MDN

Back to: JavaScript Reference > JS Loops