Loops

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false. A loop will continue running until the defined condition returns false.

while loop

The most fundamental repetition construct, present in pretty much every programming language, is the while loop. The condition is evaluated before executing the statement. The loop is run for as long as the condition is true.

Syntax

while (condition) {
  // statement
}

Example

Print all numbers up to 20.

let i = 1;

while (i <= 20) {
  console.log(i);
  i++;
}

do...while loop

The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

Syntax

do {
  // statement
} while (condition);

Example

Print all numbers up to 20.

let i = 1;

do {
  console.log(i);
  i++;
} (i <= 20)

for loop

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement to be executed in the loop.

Syntax

for (initialization; condition; finalExpression) {
  // code
}

The for loop consists of three optional expressions, followed by a code block:

  • initialization - This expression runs before the execution of the first loop, and is usually used to create a counter.

  • condition - This expression is checked each time before the loop runs. If it evaluates to true, the statement or code in the loop is executed. If it evaluates to false, the loop stops. And if this expression is omitted, it automatically evaluates to true.

  • finalExpression - This expression is executed after each iteration of the loop. This is usually used to increment a counter, but can be used to decrement a counter instead.

Any of these three expressions or the the code in the code block can be omitted.

Example

Print all numbers up to 20.

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

continue statement

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

Example

Using continue print only even numbers

for (let i = 1; i <= 20; i++) {
  if(i % 2 === 1) {
    continue;
  }
  console.log(i);
}

break statement

The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

Example

Using break exit the while loop after 100.

let i = 1;

while (true) {
  if (i > 100) {
    break;
  }

  console.log(i);
  i++;
}

References

Last updated