Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   A Short Introduction to Loops in JavaScript

JavaScript - A Short Introduction to Loops in JavaScript

Loops enable the repeated execution of a function or a block of code.

There are many types of loops in JavaScript that you can use to execute blocks of code multiple times. Each loop type has its own mechanism for controlling the beginning and the end of the loop.

To learn more about each type of loop statement, click on the corresponding statement link below.

Basic for loop example

Let’s say, for example, that we want to print the numbers 1 through 10 to the console. We could easily achieve this by simply writing ten console.log() statements, passing in the next number each time. However, this approach quickly grows in complexity – what if you need to print 100 numbers to the console, or 1,000?

Instead, a much more compact way of achieving the same result is to use a for loop statement. The following example demonstrates using a for loop to count from 1 to 10:

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

This code starts by declaring a counter variable using let i, and assigns it an initial value of 1. This is known as the initial state. This variable is then used in a comparison to determine if the code loop has completed – in the above code, the comparison used is i <= 10. As long as i is less than or equal to ten, the execution of the code continues. After this condition is checked, the code inside of the loop statement runs. After each run, the variable i is incremented by 1 (i++ ) before the loop executes again.

In each loop iteration, the value of i is different. The variable starts at a value of 1, and increments by 1 on each iteration of the loop. When i reaches the value 11, it will no longer satisfy the loop condition (i <= 10), causing the loop to end.

Once the code above has completed, the numbers 1 to 10 will have been printed to the console.

Other frequently used loops

There are multiple types of loop statements in JavaScript. These include:

  • for…in statement (used to loop through Objects)
  • for…of statement
  • do…while statement
  • while statement
  • various iteration methods for JavaScript arrays.

 

Related Articles

JavaScript – How to Use the for…in Statement

JavaScript – How to use the for…of Statement

JavaScript – How to Use if…else Statements

Get AI Code Completions for Your IDE